ReactJS调用父方法

2nbm6dog  于 2023-01-25  发布在  React
关注(0)|答案(6)|浏览(112)

我在ReactJS中迈出了第一步,试图理解父和子之间的通信。我正在制作表单,所以我有一个用于样式化字段的组件。我还有一个包含字段并检查它的父组件。示例:

var LoginField = React.createClass({
    render: function() {
        return (
            <MyField icon="user_icon" placeholder="Nickname" />
        );
    },
    check: function () {
        console.log ("aakmslkanslkc");
    }
})

var MyField = React.createClass({
    render: function() {
        ...
    },
    handleChange: function(event) {
        // call parent!
    }
})

有没有什么办法可以做到这一点。我的逻辑是好的React“世界”?谢谢你的时间。

fdx2calv

fdx2calv1#

Parent组件中的方法作为prop向下传递到Child组件。即:

export default class Parent extends Component {
  state = {
    word: ''
  }

  handleCall = () => {
    this.setState({ word: 'bar' })
  }

  render() {
    const { word } = this.state
    return <Child handler={this.handleCall} word={word} />
  }
}

const Child = ({ handler, word }) => (
<span onClick={handler}>Foo{word}</span>
)
vsmadaxz

vsmadaxz2#

React16+

子组件

import React from 'react'

class ChildComponent extends React.Component
{
    constructor(props){
        super(props);       
    }

    render()
    {
        return <div>
            <button onClick={()=>this.props.greetChild('child')}>Call parent Component</button>
        </div>
    }
}

export default ChildComponent;

父组件

import React from "react";
import ChildComponent from "./childComponent";

class MasterComponent extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state={
            master:'master',
            message:''
        }
        this.greetHandler=this.greetHandler.bind(this);
    }

    greetHandler(childName){
        if(typeof(childName)=='object')
        {
            this.setState({            
                message:`this is ${this.state.master}`
            });
        }
        else
        {
            this.setState({            
                message:`this is ${childName}`
            });
        }

    }

    render()
    {
        return <div>
           <p> {this.state.message}</p>
            <button onClick={this.greetHandler}>Click Me</button>
            <ChildComponent greetChild={this.greetHandler}></ChildComponent>
        </div>
    }
}
export default  MasterComponent;
qhhrdooz

qhhrdooz3#

为此,您将回调作为属性从父级向下传递给子级。
例如:

var Parent = React.createClass({

    getInitialState: function() {
        return {
            value: 'foo'
        }
    },

    changeHandler: function(value) {
        this.setState({
            value: value
        });
    },

    render: function() {
        return (
            <div>
                <Child value={this.state.value} onChange={this.changeHandler} />
                <span>{this.state.value}</span>
            </div>
        );
    }
});

var Child = React.createClass({
    propTypes: {
        value:      React.PropTypes.string,
        onChange:   React.PropTypes.func
    },
    getDefaultProps: function() {
        return {
            value: ''
        };
    },
    changeHandler: function(e) {
        if (typeof this.props.onChange === 'function') {
            this.props.onChange(e.target.value);
        }
    },
    render: function() {
        return (
            <input type="text" value={this.props.value} onChange={this.changeHandler} />
        );
    }
});

在上面的例子中,Parent使用valueonChange属性调用ChildChild返回绑定onChange处理程序到标准<input />元素,并将值向上传递到Parent的回调函数(如果定义了)。
因此,ParentchangeHandler方法被调用,第一个参数是Child<input />字段的字符串值。结果是Parent的状态可以用该值更新,从而导致父元素的<span />元素在您在Child的输入字段中键入新值时用新值更新。

pprl5pva

pprl5pva4#

2019更新react 16+和ES6

由于React.createClass从react版本16中被弃用,新的Javascript ES6将给您带来更多好处。
母体

import React, {Component} from 'react';
import Child from './Child';
  
export default class Parent extends Component {

  es6Function = (value) => {
    console.log(value)
  }

  simplifiedFunction (value) {
    console.log(value)
  }

  render () {
  return (
    <div>
    <Child
          es6Function = {this.es6Function}
          simplifiedFunction = {this.simplifiedFunction} 
        />
    </div>
    )
  }

}

儿童

import React, {Component} from 'react';

export default class Child extends Component {

  render () {
  return (
    <div>
    <h1 onClick= { () =>
            this.props.simplifiedFunction(<SomethingThatYouWantToPassIn>)
          }
        > Something</h1>
    </div>
    )
  }
}

将无状态子进程简化为ES6常量

import React from 'react';

const Child = (props) => {
  return (
    <div>
    <h1 onClick= { () =>
        props.es6Function(<SomethingThatYouWantToPassIn>)
      }
      > Something</h1>
    </div>
  )

}
export default Child;
l7mqbcuq

l7mqbcuq5#

您可以使用任何父方法。为此,您应该像发送任何简单值一样将这些方法从父方法发送到子方法。并且您可以同时使用父方法中的多个方法。例如:

var Parent = React.createClass({
    someMethod: function(value) {
        console.log("value from child", value)
    },
    someMethod2: function(value) {
        console.log("second method used", value)
    },
    render: function() {
      return (<Child someMethod={this.someMethod} someMethod2={this.someMethod2} />);
    }
});

并像这样将其用于Child(用于任何操作或任何子方法):

var Child = React.createClass({
    getInitialState: function() {
      return {
        value: 'bar'
      }
    },
    render: function() {
      return (<input type="text" value={this.state.value} onClick={this.props.someMethod} onChange={this.props.someMethod2} />);
    }
});
b4lqfgs4

b4lqfgs46#

使用功能||无状态组件
父组件

import React from "react";
 import ChildComponent from "./childComponent";

 export default function Parent(){

     const handleParentFun = (value) =>{
       console.log("Call to Parent Component!",value);
     }

     return (
         <>
             This is Parent Component
             <ChildComponent 
                 handleParentFun = {(value) => {
                     console.log("your value -->",value);
                     handleParentFun(value);
                 }}
             />
         </>
     );
 }

子组件

import React from "react";

export default function ChildComponent(props){
    return(
        <> 
           This is Child Component 
           <button onClick={props.handleParentFun("Your Value")}>
               Call to Parent Component Function
           </button>
        </>
    );
}

相关问题