关于react props传值的问题

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是只读不可修改的,请问这样写可以吗

阅读 2.7k
3 个回答

可以,只要能正常运行不报错,都可以.
不过不建议这么玩,React 推荐单向数据流,像你这么玩的话,有可能会造成数据难以跟踪,降低程序的可维护性,当出现 bug 时不容易定位等问题.

既然用react就要遵循它单向数据流的概念...就不要违背人家的设计初衷...

新手上路,请多包涵

建议使用redux来管理props数据

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题