react 父组件与子组件通信

1.父(UserListContainer)到子(UserList)

class UserList extends React.Component{

    render(){
        return(
            <div>
                <ul>
                    {
                        this.props.users.map(function(user){return(
                                <li key={user.id}>
                                    {user.name}    
                                </li>)})
                    }
                </ul>
            </div>
        );
    }
}
class UserListContainer extends React.Component{
    
    constructor(props){
        super(props);
        this.state={
            users:[]
        }
    }

    componentDidMount(){
        fetch('url').then(
           response=>{response.json().then(data=>{this.setState({users:data})})}    
        );
    }
    render({
           return(
                <UserList users="{this.state.users}">
            );
        });
}

通过给子组件的属性赋值,将参数传给子组件的props。

2.子组件传给父组件

原理:父组件定义一个方法并绑定this作用域,将方法传给子组件。子组件在调用方法,在方法中将数据以参数的形式传给父组件。

class UserListContainer extends React.Component{
    
    constructor(props){
        super(props);
        this.state={
            users:[]
        }
        this.handleAddUser = this.handleAddUser.bind(this);
    }

    //新增用户
    handleAddUser(user){
        fetch("url",{
            method:'pose',
            body:JSON.stringify({User:user})
        }).then(response=>{response.json().then(function(newUser){
                    this.setState((preState)=>({users: preState.users.concat([newUser])}))
                })})
    }

    componentDidMount(){
        fetch('url').then(
           response=>{response.json().then(data=>{this.setState({users:data})})}    
        );
    }
    render({
           return(
                <UserList addUser="{this.handleAddUser}" users="{this.state.users}">
            );
        });
}
class UserList extends React.Component{

    constructor(props){
        super(props);
        this.add= this.add.bind(this);
    }
    
    add(){
        this.props.onAddUser(name); 
    }
    
    render(){
        return(
            <div>
                <div>
                    <ul>
                        {
                            this.props.users.map(function(user){return(
                                    <li key={user.id}>
                                        {user.name}    
                                    </li>)})
                        }
                    </ul>
                <div>
                <div Onclick="this.add">add</div>
            </div>
        );
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值