觸發子組件方法
第一種辦法:
class App extends React.Component{ render(){ return ( <React.Fragment> <button className="btn" onClick={this.clear.bind(this)}>清空</button> <Input ref="input"></Input> </React.Fragment> ) } clear(){ //通過refs拿到input組件對象,調用下面的方法 this.refs.input.clear() } }
第二種辦法:
我們知道在子組件中可以通過 this.props.methodName 調用父組件方法
因此我們可以通過給子組件props添加一個事件,在子組件的constructor中執行,將子組件的this作為參數傳入,這樣我們就可以在父組件中拿到子組件中的this
舉例:有Input組件,內部有clear方法,我們需要在Input外層觸發Input組件內部的clear去清空當前輸入框
class App extends React.Component{ render(){ return ( <React.Fragment>
<button className="btn" onClick={this.clear.bind(this)}>清空</button>
<Input inputEvent={this.inputEvent.bind(this)}></Input>
</React.Fragment>
) } inputEvent(input){ //將子組件對象綁定到父組件的$child屬性,這個屬性名可以自己隨便起
this.$child = input } clear(){ //點擊按鈕觸發子組件clear方法
this.$child.clear() } }
在Input組件中
class InputComponent extends React.Component{ constructor(props){ super(props) this.state = { inputVal: '' } //執行父組件的方法,將this傳過去
this.props.inputEvent(this) } render(){ return ( <div className="input-container">
<input type="text" value={this.state.inputVal} onChange={this.inputChangeHandler.bind(this)} />
</div>
) } inputChangeHandler(e){ this.setState({ inputVal: e.target.value }) } clear(){ this.setState({ inputVal: '' }) } }
觸發兄弟組件的方法
原理和上面類似,假設父組件A有子組件B和C,如果要在B中觸發C的方法,需要將C的實例通過props傳遞給A,然后在B中調用props觸發A的方法,間接觸發C
實例:Input組件中點擊按鈕后需要在List組件中添加一條數據:
父組件:
class App extends React.Component{ render(){ return ( <React.Fragment>
<button className="btn" onClick={() => this.$child_input.clear()}>清空</button>
<Input inputEvent={input => this.$child_input = input} addEvent={item => this.$child_list.addRecord(item)}></Input>
<List listEvent={list => this.$child_list = list}></List>
</React.Fragment>
) } }
Input組件:
class InputComponent extends React.Component{ constructor(props){ super(props) this.state = { inputVal: '' } this.props.inputEvent(this) } render(){ return ( <div className="input-container">
<input type="text" value={this.state.inputVal} onChange={this.inputChangeHandler.bind(this)} />
<button className="btn" onClick={() => this.props.addEvent(this.state.inputVal) }>Submit</button>
</div>
) } inputChangeHandler(e){ this.setState({ inputVal: e.target.value }) } clear(){ this.setState({ inputVal: '' }) } }
List組件:
class MyList extends React.Component{ constructor(props){ super(props) this.state = { data: [ 'Racing car sprays burning fuel into crowd.', 'Japanese princess to wed commoner.', 'Australian walks 100km after outback crash.', 'Man charged over missing wedding girl.', 'Los Angeles battles huge wildfires.' ] } this.props.listEvent(this) } render(){ return ( <ul className="list-container"> {this.state.data.map((item, index) => ( <li key={index}>{item}</li>
))} </ul>
) } addRecord(item){ this.setState({ data: [...this.state.data, item] }) } }