umi搭建react+antd專案(六)父子元件通訊
阿新 • • 發佈:2018-12-25
上一篇寫了一個子元件,只是把值傳入進來,這篇講解在子元件修改父元件的資料
1.在index.js裡,新增方法:updateImg 用於修改list集合
updateImg() {
this.setState({
list: [
{
"src": "http://dummyimage.com/468x60"
}
]
});
}
在子元件上傳入該方法:
<ListComponent updateImg={this.updateImg.bind(this)} list={this.state.list}/>
完整程式碼:
import React, {Component} from 'react'; import Link from 'umi/link'; import instance from '../conf/axiosConf'; import ListComponent from '../component/list' export default class index extends Component { constructor(props) { super(props); this.state = { list: [] } } componentDidMount() { instance.get("api/img").then(data => { this.setState({list: data.list}); }) } updateImg() { this.setState({ list: [ { "src": "http://dummyimage.com/468x60" } ] }); } render() { return ( <div> <Link to="/index2"> index </Link> { this.state.list.map((entry, index) => <div key={`list-${index}`}>{entry.src}</div> ) } <br/> <div> <ListComponent updateImg={this.updateImg.bind(this)} list={this.state.list}/> </div> </div> ) } }
2.修改子元件
import React, {Component} from 'react'; export default class List extends Component { constructor(props) { super(props); } render() { return ( <div> <button onClick={this.props.updateImg}>切換資料</button> { this.props.list.map((entry, index) => <div key={`list-${index}`}>{entry.src}</div> ) } </div> ) } }