Javascript ReactJS 调用父方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26176519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:28:06  来源:igfitidea点击:

ReactJS call parent method

javascriptreactjs

提问by KaronatoR

I'm making my first step in ReactJS and trying to understand communication between parent and children. I'm making form, so I have the component for styling fields. And also I have parent component that includes field and checking it. Example:

我正在 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!
    }
})

Is there any way to do it. And is my logic is good in reactjs "world"? Thanks for your time.

有什么办法可以做到。我的逻辑在reactjs“世界”中是否良好?谢谢你的时间。

回答by Mike Driver

To do this you pass a callback as a property down to the child from the parent.

为此,您将回调作为属性从父级传递给子级。

For example:

例如:

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} />
        );
    }
});

In the above example, Parentcalls Childwith a property of valueand onChange. The Childin return binds an onChangehandler to a standard <input />element and passes the value up to the Parent's callback if it's defined.

在上面的示例中,Parent调用Child具有valueand属性onChange。的Child回报结合一个onChange处理程序,以一个标准的<input />元件,并传递值到Parent如果它定义的回调函数。

As a result the Parent's changeHandlermethod is called with the first argument being the string value from the <input />field in the Child. The result is that the Parent's state can be updated with that value, causing the parent's <span />element to update with the new value as you type it in the Child's input field.

因此,ParentchangeHandler方法被调用,第一个参数是 中<input />字段的字符串值Child。结果是Parent可以使用该值更新 的状态,从而导致父<span />元素在您在Child的输入字段中键入时使用新值进行更新。

回答by Vitaliy Andrusishyn

You can use any parent methods. For this you should to send this methods from you parent to you child like any simple value. And you can use many methods from the parent at one time. For example:

您可以使用任何父方法。为此,您应该像任何简单的值一样将这些方法从您的父母发送给您的孩子。并且您可以一次使用来自父级的多种方法。例如:

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} />);
    }
});

And use it into the Child like this (for any actions or into any child methods):

并像这样在 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} />);
    }
});

回答by Fangming

2019 Update with react 16+ and ES6

2019 更新 React 16+ 和 ES6

Posting this since React.createClassis deprecated from react version 16 and the new Javascript ES6 will give you more benefits.

发布此内容是因为React.createClassReact 版本 16 已弃用,新的​​ Javascript ES6 将为您带来更多好处。

Parent

家长

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>
    )
  }

}

Child

孩子

import React, {Component} from 'react';

export default class Child extends Component {

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

Simplified stateless child as SE6 constant

将无状态子节点简化为 SE6 常量

import React from 'react';

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

}
export default Child;

回答by Jonca33

Pass the method from Parentcomponent down as a propto your Childcomponent. ie:

Parent组件中的方法作为 aprop传递给您的Child组件。IE:

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>
)

回答by Omkesh Sajjanwar

Using Function || stateless component

使用函数 || 无状态组件

Parent Component

父组件

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

 export default function Parent(){

 const handleParentFun = () =>{
   console.log("Call to Parent Component!");
 }
 return (<>
           This is Parent Component
           <ChildComponent 
             handleParentFun={handleChildFun}
           />
        </>);
}

Child Component

子组件

import React from "react";


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

回答by Sandeep Shekhawat

React 16+

反应 16+

Child Component

子组件

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;

Parent Component

父组件

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;