react里子組件不能直接操作父組件的數據。
所以要從父組件傳遞一個方法給子組件,
子組件獲取到該方法后,把子數據傳入該方法,
父組件才能獲取到子數據
例子:
子組件 Child.js
import React, { Component } from 'react' class Child extends Component{ constructor(props){ super(props) this.state = { cdata:"子組件數據" } } render(){ return( <div> <button onClick={this.trans.bind(this,this.state.cdata)}>確定</button> </div> ) } //點擊子組件時,定義一個方法,調用父組件傳過來的方法,把子組件數據傳入到這個方法里 trans(data){ this.props.content(data) } } export default Child;
父組件App.js
import React, { Component } from 'react'; import Child from './Child' class App extends Component{ constructor(props){ super(props) this.state = { pdata:"父組件數據" } } render(){ return( <div> {/* 傳遞一個方法給子組件 */} <Child content={this.getValue.bind(this)}></Child> {this.state.pdata} </div> ) } //在方法里傳入一個參數,val就是子組件傳過來的數據 getValue(val){ this.setState({ pdata:val }) } } export default App;
使用箭頭函數的寫法
子組件:
import React, { Component } from 'react'; class Child extends Component { constructor(props) { super(props); this.state = { cdata:"子數據" } } render() { return ( <div> 子組件 <button onClick={()=>this.transValue(this.state.cdata)}>傳遞數據</button> </div> ); } transValue(val){ console.log(val); this.props.content(val) } } export default Child;
父組件
import React, { Component } from 'react'; import Child from './Child' class App extends Component { constructor(props) { super(props); this.state = { pdata:"父數據" } } render() { return ( <div> {this.state.pdata} {/* 這個方法要傳入參數 */} <Child content={(val)=>this.giveMeth(val)}></Child> </div> ); } giveMeth(val){ console.log(val); } } export default App;