这是一个binding
问题,您需要bind
上下文,否则this
将不会指向react组件。使用.bind(this)
withfunction
或 usearrow function
来避免此类问题。用这个:
render(){
var userNodes = this.props.posts.map(function(user, i){
return (
<tr onClick={() => this.handleClick(user)}>
<Td>{user.postId}</Td>
<Td>{user.title}</Td>
<Td>{user.body}</Td>
</tr>
)
}.bind(this));
或这个:
render(){
var userNodes = this.props.posts.map((user, i) => {
return (
<tr onClick={() => this.handleClick(user)}>
<Td>{user.postId}</Td>
<Td>{user.title}</Td>
<Td>{user.body}</Td>
</tr>
)
});
检查工作示例:
class App extends React.Component{
handleClick(user){
console.log(user);
}
render(){
var data = [0,1,2,3,4].map((user, i) => {
return (
<tr onClick={() => this.handleClick(user)}>
<td>{user}</td>
<td>{user}</td>
<td>{user}</td>
</tr>
)
});
return(
<table>
<thead>
<th>A</th>
<th>B</th>
<th>C</th>
</thead>
<tbody>
{data}
</tbody>
</table>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'/>