class Parent extends React.Component {
constructor(){
this.method = {};
}
render() {
return <Child method={this.method}/>
}
}
class Child extends React.Component {
getMsg = () => {
console.log('111');
}
componentDidMount() {
this.props.method && (this.props.method.getMsg = this.getMsg);
}
render() {
return (
...
)
}
}
react中说props是只读不可修改的,请问这样写可以吗
可以,只要能正常运行不报错,都可以.
不过不建议这么玩,React 推荐单向数据流,像你这么玩的话,有可能会造成数据难以跟踪,降低程序的可维护性,当出现 bug 时不容易定位等问题.