美文网首页
react-子组件与父组件

react-子组件与父组件

作者: 折纸飞机 | 来源:发表于2019-04-23 09:07 被阅读0次

    子组件改变父组件的state
    class Parent extends Component{
    state = {
    msg: 'start'
    };
    render() {
    return <Child_1 msg={this.state.msg} />;
    }
    }
    class Child_1 extends Component{
    render() {
    return <p>{this.props.msg}</p>
    }
    }

    父组件改变子组件的内容
    class Parent extends Component{
    render() {
    return <Child_1 inputPlaceholder="请输入" />;
    }
    }
    class Child_1 extends Component{
    render() {
    const { inputPlaceholder } = this.props;
    return <input placeholder={inputPlaceholder} />
    }
    }

    父组件调用子组件的方法
    方法一:
    import React, {Component} from 'react';
    export default class Parent extends Component {
    render() {
    return(
    <div>
    <Child onRef={this.onRef} />
    <button onClick={this.click} >click</button>
    </div>
    )
    }
    onRef = (ref) => {
    this.child = ref
    }
    click = (e) => {
    this.child.myName()
    }
    }
    class Child extends Component {
    componentDidMount(){
    this.props.onRef(this)
    }
    myName = () => alert('xiaohesong')
    render() {
    return ('wo')
    }
    }
    方法二:
    import React, {Component} from 'react';
    export default class Parent extends Component {
    click = () => {
    this.divRef.myName();
    }
    render() {
    return(
    <div ref={refs => this.divRef =refs}> />
    )
    }
    }
    class Child extends Component {
    myName = () => alert('xiaohesong')
    }

    子组件调用父组件的方法
    class Parent extends Component{
    onChange = (value) => {
    ...
    }
    }
    class Child extends Component{
    this.props.onChange(value);
    }

    父组件引用多个相同子组件,分别向该子组件传值的方法
    class Parent extends Component{
    onChange = (value) => {
    ...
    }
    render() {
    return (
    <div>
    <Child showStatus={0} />
    <Child showStatus={1} />
    </div>
    )
    }
    }
    class Child extends Component{
    componentDidMount() {
    const showStatus = this.props.showStatus;
    if (showStatus === 0) {
    } else if (showStatus === 1) {
    }
    }
    }

    相关文章

      网友评论

          本文标题:react-子组件与父组件

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