2016-05-12 21 views
0

如何在调用React组件的函数时给出该组件的变量?我有一个Parent,通过Test类到Child组件,并且这个孩子想要改变Test中的东西。从声明为变量的React组件调用函数

export class Parent extends React.Component { 
    render() { 
     let test = (<Test />); 
     return (<Child tester={test} />); 
    } 
} 

export class Child extends React.Component { 
    render() { 
     this.props.tester.setText("qwerty"); // how to invoke setText, setState or something like that? 
     return ({this.props.tester}); 
    } 
} 

export class Test extends React.Component { 
    constructor(props) { 
     super(props); 

     this.state = { 
      text: this.props.text || "" 
     }; 
    } 

    setText(text) { 
     this.setState({ text: text }); 
    } 

    render() { 
     return (<div>{this.state.text}</div>); 
    } 
} 
+0

你想在'Test'中改变什么?你可以通过你想要改变的所有东西作为道具并立即渲染。不需要功能。 –

+0

我想在'Child'里传递一些东西,其中'Test'只是从'Parent'传递的对象的引用。我不能简单地'this.props.tester.text =“sth”' – Nickon

回答

0

我认为你应该考虑反应组件的生命周期。
请尝试下面的代码(我刚刚添加日志记录),并仔细观察日志。

export class Parent extends React.Component { 
    render() { 
     let test = (<Test />); 
     return (<Child tester={test} />); 
    } 
} 

export class Child extends React.Component { 
    render() { 
     console.log("Child render"); // <= logging added! 
     // this.props.tester.setText("qwerty"); 
     // What kind of object is 'this.props.tester(= <Test />)' here??? 
     return ({this.props.tester}); 
    } 
} 

export class Test extends React.Component { 
    constructor(props) { 
     super(props); 
     console.log("Test constructor"); // <= logging added! 
     this.state = { 
      text: this.props.text || "" 
     }; 
    } 

    setText(text) { 
     // this.setState({ text: text }); 
     // this is another problem. We cannot call setState before mounted. 
     this.state.text= text; 
    } 

    render() { 
     return (<div>{this.state.text}</div>); 
    } 
} 

如果是这样,你会看到2个重要事实。

  1. 当您调用'setText'时,'Test'组件尚未实例化。
    我们如何调用未实例化的对象的方法?不能!
  2. 这意味着'this.props.tester'不是'Test'组件的实例。

但是,如果你真的想要执行你的代码,像这样修改Child.render。

render() { 
    var test = new Test({props:{}}); 
    // or even this can work, but I don't know this is right thing 
    // var test = new this.props.tester.type({props:{}}); 
    test.setText("qwerty"); 
    return test.render(); 
} 

但我不认为这是一个好方法。

从另一个角度来看,人们可以想出一个主意像,

render() { 
    // Here, this.props.tester == <Test /> 
    this.props.tester.props.text = "qwerty"; 
    return (this.props.tester); 
} 

,但当然这是不可能的,因为“this.props.tester”是只读的儿童属性。