2016-05-12 28 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」是隻讀的兒童屬性。