觸發子組件方法this
第一種辦法:spa
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() } }
第二種辦法:code
咱們知道在子組件中能夠經過 this.props.methodName 調用父組件方法對象
所以咱們能夠經過給子組件props添加一個事件,在子組件的constructor中執行,將子組件的this做爲參數傳入,這樣咱們就能夠在父組件中拿到子組件中的thisblog
舉例:有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組件中ci
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: '' }) } }
觸發兄弟組件的方法get
原理和上面相似,假設父組件A有子組件B和C,若是要在B中觸發C的方法,須要將C的實例經過props傳遞給A,而後在B中調用props觸發A的方法,間接觸發Cinput
實例:Input組件中點擊按鈕後須要在List組件中添加一條數據:it
父組件:
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] }) } }