我试图从一个子组件发送数据到它的父母如下:

const ParentComponent = React.createClass({
    getInitialState() {
        return {
            language: '',
        };
    },
    handleLanguageCode: function(langValue) {
        this.setState({language: langValue});
    },

    render() {
         return (
                <div className="col-sm-9" >
                    <SelectLanguage onSelectLanguage={this.handleLanguage}/> 
                </div>
        );
});

这是子组件:

export const SelectLanguage = React.createClass({
    getInitialState: function(){
        return{
            selectedCode: '',
            selectedLanguage: '',
        };
    },

    handleLangChange: function (e) {
        var lang = this.state.selectedLanguage;
        var code = this.state.selectedCode;
        this.props.onSelectLanguage({selectedLanguage: lang});   
        this.props.onSelectLanguage({selectedCode: code});           
    },

    render() {
        var json = require("json!../languages.json");
        var jsonArray = json.languages;
        return (
            <div >
                <DropdownList ref='dropdown'
                    data={jsonArray} 
                    value={this.state.selectedLanguage}
                    caseSensitive={false} 
                    minLength={3}
                    filter='contains'
                    onChange={this.handleLangChange} />
            </div>            
        );
    }
});

我需要的是在父组件中获得用户所选择的值。我得到这个错误:

Uncaught TypeError: this.props.onSelectLanguage is not a function

有人能帮我找到问题吗?

附注:子组件正在从json文件中创建下拉列表,我需要下拉列表来显示json数组的两个元素相邻(如:“aaa,英语”作为首选!)

{  
   "languages":[  
      [  
         "aaa",
         "english"
      ],
      [  
         "aab",
         "swedish"
      ],
}

当前回答

使用Callback将数据从子组件传递给父组件

You need to pass from parent to child callback function, and then call it in the child.

父组件:-TimeModal

  handleTimeValue = (timeValue) => {
      this.setState({pouringDiff: timeValue});
  }

  <TimeSelection 
        prePourPreHours={prePourPreHours}
        setPourTime={this.setPourTime}
        isPrePour={isPrePour}
        isResident={isResident}
        isMilitaryFormatTime={isMilitaryFormatTime}
        communityDateTime={moment(communityDT).format("MM/DD/YYYY hh:mm A")}
        onSelectPouringTimeDiff={this.handleTimeValue}
     />

注意:- onSelectPouringTimeDiff = {this.handleTimeValue}

在子组件中,当需要时调用props

 componentDidMount():void{
      // Todo use this as per your scenrio
       this.props.onSelectPouringTimeDiff(pouringDiff);  
  }

其他回答

您甚至可以避免父函数直接更新状态

在父组件中:

render(){
 return(<Child sendData={ v => this.setState({item: v}) } />);
}

在子组件中:

demoMethod(){
   this.props.sendData(value);
}

在这里,我试图用最简单的方式解释: 我正在从子组件更新父组件计数器。

父组件(propapp .jsx)

import React, { useState } from 'react'
import Child from './Child'

export default function PropsApp(){
   const [counter, setCounter] = useState(0)

   const updateMyCounter = () => {
       setCounter(counter + 1)
   }

   return(
    <>  
        <hr></hr>
        <h1>This is Parent</h1>
        <h2>{counter}</h2>
        <Child updateParent={updateMyCounter} />
    </>
   )
}

子组件(Child.jsx)

export default function Child(props){

return(
    <>  
        <hr></hr>
        <h1>This is Child</h1>
        <button
            onClick={props.updateParent}
        >
            Update Parent Component
        </button>
    </>
   )
}

单击Update父组件并查看神奇的效果

在React中,将数据从子组件传递给父组件:

从接收值的父节点向子节点传递一个函数。 当子组件中的值发生变化时,调用该函数 使用更新后的值。

e.g.

const Parent = () => {

  const handleChange = values => {
     alert(JSON.stringify(values) );
     //do something with the values  
  }

  return (
    <Child handleChange={handleChange} />
  );
}

const Child = ({handleChange}) => {
    return (
        <button onClick={()=> handleChange('values you wish to pass') }}></button>
    );
}

注意:从react 16开始,我建议在几乎所有情况下都使用功能组件。

考虑到React函数组件和使用钩子现在越来越流行,我将给出一个简单的例子,说明如何将数据从子组件传递给父组件

在父函数组件中,我们将有:

import React, { useState } from "react";

then

const [childData, setChildData] = useState("");

和传递setChildData(它们的工作与此类似。setState在类组件)到子

return( <ChildComponent passChildData={setChildData} /> )

在子组件中,我们首先获得接收道具

function ChildComponent(props){ return (...) }

然后,您可以像使用处理程序函数一样以任何方式传递数据

const functionHandler = (data) => {

props.passChildData(data);

}

从子组件到父组件,如下所示

父组件

class Parent extends React.Component {
   state = { message: "parent message" }
   callbackFunction = (childData) => {
       this.setState({message: childData})
   },
   render() {
        return (
            <div>
                 <Child parentCallback = {this.callbackFunction}/>
                 <p> {this.state.message} </p>
            </div>
        );
   }
}

子组件

class Child extends React.Component{
    sendBackData = () => {
         this.props.parentCallback("child message");
    },
    render() { 
       <button onClick={sendBackData}>click me to send back</button>
    }
};

我希望这能起作用