试图将函数传递给子组件时,该函数是未定义的。实际上,我什至无法在班上直接执行它。您认为有错字吗?
class FriendsPage extends Component {
constructor(props){
super(props);
this.mylog = this.mylog.bind(this);
}
mylog(){
console.log("test debug");
}
renderItem(item) {
return (<User friend={item} key={item.id} mylog={this.mylog}/>);
}
class User extends Component {
constructor(props){
super(props);
}
render() {
this.props.mylog(); // <== This is undefined
...
}
工作正常。虽然,如果您尝试在任何其他位置渲染<User />
,而无需prop
命名mylog
,则将不确定。
class FriendsPage extends React.Component {
constructor(props) {
super(props);
this.mylog = this.mylog.bind(this);
}
mylog() {
console.log("test debug");
}
render() {
return ( < User mylog = {
this.mylog
}
/>);
}
}
class User extends React.Component {
constructor(props) {
super(props);
}
render() {
this.props.mylog();
return <h1 > Hello < /h1>;
}
}
ReactDOM.render( < FriendsPage / > , document.getElementById('root'));
<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="root"></div>