美文网首页
react 父子组件修改值

react 父子组件修改值

作者: this_smile | 来源:发表于2019-08-08 17:47 被阅读0次

父组件

class Father extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            childChangeFather: '当前点击的是:#',
            list: [
                {id: 1, text: '1'},
                {id: 2, text: '2'},
                {id: 3, text: '3'}
            ],
            fatherChangeChildData: '父传子:#'
        }
    }

    onChangeState(item) {
        this.setState((state) => ({
                childChangeFather: '当前点击的是:' + item.text,
                fatherChangeChildData: '父传子:' + item.text
        }))
    }

    render() {
        return (
            <div>
                <p>内容:{this.state.childChangeFather}</p>
                <Child list={this.state.list} fatherChangeChild={this.state.fatherChangeChildData} onClick={i => this.onChangeState(i)}/>
            </div>
        )
    }
}

子组件

class Child extends React.Component {
    componentWillReceiveProps(nextProps){
        this.setState({
            fatherChangeChildData: nextProps.fatherChangeChild
        })
    }
    render(){
        return (
            <ul>
                {
                    this.props.list.map((item) => (
                        <li key={item.id} onClick={() => this.props.onClick(item)}>{item.text}</li>
                    ))
                }
                <span>{this.props.fatherChangeChild}</span>
            </ul>
        )
    }
}

相关文章

  • react 父子组件修改值

    父组件 子组件

  • React入门(二)组件

    本节知识点 (1)React组件化 (2)React父子组件传值 (一)组件 在React中组件都是对应的一个个类...

  • react-父子组件间通信

    React-父子组件间通信 父组件传 值 给子组件, 传 方法 给子组件 子组件接收 值 ,触发父组件的 方法

  • vue、react对比

    一、父子通信 1. 父组件通过props向子组件传值 vue:父组件 子组件接收 react:父组件: 子组件: ...

  • react 父子组件传值(兄弟传值)

    react中父子组件传值 父向子: 父组件通过自定义属性向子组件传值,子组件通过this.props.属性名接收子...

  • React中的Refs & DOM

    在React数据流中,父子组件唯一的交流方式是通过props属性;如果要修改子组件,通过修改父组件的属性,更新达到...

  • 学习react的第二天(1)

    react组件传值 为了防止数据乱流,react规定,不借助外力,只支持父子传值 父 -> 子 1. 在父元素中,...

  • React父子组件间的传值的方法

    在单页面里面,父子组件传值是比较常见的,这篇文章主要介绍了React父子组件间的传值的方法,小编觉得挺不错的,现在...

  • react Consumer Provider

    跨几个组件传递值或者方法的时候, 如果依赖父子组件传值, 那势必会很麻烦. 好在react提供了Provider ...

  • 组件二

    父子组价的通信 父传子通过props, 组件的props只读,组件本身不能修改他的props 所有 React 组...

网友评论

      本文标题:react 父子组件修改值

      本文链接:https://www.haomeiwen.com/subject/gwgxjctx.html