后端开发学React - 4 父子组件传值
4.1 组件拆分
这里将之前的注册球队应用进行拆分
拆为两个模块(暂时去掉互相传值调用)
- 父模块:
PremierLeagueRegister.js
- 子模块:
PremierLeagueRegisterItem.js
1. 父模块
- PremierLeagueRegister.js
import React, { Component, Fragment } from 'react'
import PremierLeagueRegisterItem from './PremierLeagueRegisterItem'
class PremierLeagueRegister extends Component {
constructor(props) {
super(props)
this.state = {
inputValue: '',
list:['曼城','切尔西']
}
}
render() {
return (
<Fragment>
<input value={this.state.inputValue} onChange={this.inputChange.bind(this)}/>
<button onClick={this.addList.bind(this)}>注册球队</button>
{/*修改点*/}
<PremierLeagueRegisterItem />
</Fragment>
)
}
inputChange(e){
this.setState(
{
inputValue:e.target.value
}
)
}
addList(e){
this.setState({
list:[...this.state.list,this.state.inputValue],
inputValue:''
})
}
deleteItem(index){
let list = this.state.list
list.splice(index,1)
this.setState({
list:list
})
}
}
export default PremierLeagueRegister
2. 子模块
- PremierLeagueRegisterItem.js
import React, { Component } from 'react';
class PremierLeagueRegisterItem extends Component {
constructor(props) {
super(props)
}
render() {
return (
<ul>
<li>阿森纳</li>
</ul>
);
}
}
export default PremierLeagueRegisterItem;
4.2 父子组件传值
拆分后,添加和删除均不好用
需要完成两个事情:
- 父组件传递参数给子组件
- 子组件调用父组件方法
1. 父组件传递参数给子组件
公式
父.js:<子 自定义变量a={this.state.list}/>
子.js:this.props.自定义变量a
2. 子组件调用父组件方法
子组件是不能给父组件传值的,所以只能调用父组件方法
公式
父.js:<子 this.父方法.bind(this)/>
子.js:
<input onClick={ this.子方法.bind(this,参数) } />
子方法(){ this.props.父方法(参数) }
3. 代码实例
- PremierLeagueRegister.js
import React, { Component, Fragment } from 'react'
import PremierLeagueRegisterItem from './PremierLeagueRegisterItem'
class PremierLeagueRegister extends Component {
constructor(props) {
super(props)
this.state = {
inputValue: '',
list:['曼城','切尔西']
}
}
render() {
return (
<Fragment>
<input value={this.state.inputValue} onChange={this.inputChange.bind(this)}/>
<button onClick={this.addList.bind(this)}>注册球队</button>
<PremierLeagueRegisterItem
//父组件向子组件传递参数
contentList={this.state.list}
//子组件调用父组件方法
deleteItem={this.deleteItem.bind(this)}
/>
</Fragment>
)
}
inputChange(e){
this.setState(
{
inputValue:e.target.value
}
)
}
addList(e){
this.setState({
list:[...this.state.list,this.state.inputValue],
inputValue:''
})
}
deleteItem(index){
let list = this.state.list
list.splice(index,1)
this.setState({
list:list
})
}
}
export default PremierLeagueRegister
- PremierLeagueRegisterItem.js
import React, { Component } from 'react';
class PremierLeagueRegisterItem extends Component {
render() {
return (
<ul>
{
//子组件接受父组件传递的参数
this.props.contentList.map(
(item,index)=>{
return (
//子组件调用自己方法
<li key={index+item} onClick={this.clickItem.bind(this,index)}>
{item}
</li>
)
}
)
}
</ul> );
}
clickItem(index){
//子组件调用父组件方法
this.props.deleteItem(index)
}
}
export default PremierLeagueRegisterItem;