Reputation: 1495
Looking at the docs regarding functional vs classical components, it seems you only need classical components if you want to create an instance that gives you access to this
or you want the lifecycle methods. Does that mean a functional component can only have a render inside? If it needs to handle a click, it has to go through a onClick
listener on the markup that links directly to its props and there's no way to go through a handleClick
function?
const Type = ({onTypeClick, name}) => {
<li
onClick={onTypeClick.bind(null, name)}
>
{name}
</li>
}
VS
const Type = React.createClass({
handleClick (e) {
e.preventDefault()
this.props.onTypeClick(this.props.name)
},
render() {
return (
<li onClick={handleClick}>
{this.props.name}
</li>
)
}
})
Upvotes: 1
Views: 147
Reputation: 20614
A stateless component returns the result of render function, however it's just a function so it has access to stuff in closure.
const handleClick = (e, props) => {
e.preventDefault()
props.onTypeClick(props.name)
}
const Type = props => {
// don't forget to return!
return (
<li onClick={event => handleClick(event, props)}>
{props.name}
</li>
)
}
Upvotes: 1