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

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"
      ],
}

当前回答

考虑到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);

}

其他回答

反应。在React的新版本中,createClass方法已经被弃用了,你可以用下面的方法很简单地让一个函数组件和另一个类组件来维护状态:

家长:

const ParentComp = () => { getLanguage = (language) => { console.log('父组件中的语言:',Language); } < ChildComp onGetLanguage = {getLanguage} };

孩子:

class ChildComp extends React.Component { state = { selectedLanguage: '' } handleLangChange = e => { const language = e.target.value; thi.setState({ selectedLanguage = language; }); this.props.onGetLanguage({language}); } render() { const json = require("json!../languages.json"); const jsonArray = json.languages; const selectedLanguage = this.state; return ( <div > <DropdownList ref='dropdown' data={jsonArray} value={tselectedLanguage} caseSensitive={false} minLength={3} filter='contains' onChange={this.handleLangChange} /> </div> ); } };

考虑到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);

}

其思想是向子程序发送回调,该子程序将被调用以返回数据

一个使用函数的完整且最小的示例:

App将创建一个子程序,它将计算一个随机数并直接将其发送回父程序,父程序将console.log结果

const Child = ({ handleRandom }) => {
  handleRandom(Math.random())

  return <span>child</span>
}
const App = () => <Child handleRandom={(num) => console.log(num)}/>

使用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);  
  }

在React v16.8+函数组件中,你可以使用useState()来创建一个函数状态,让你更新父状态,然后将它作为props属性传递给子组件,然后在子组件中你可以触发父状态函数,下面是一个工作代码片段:

const { useState , useEffect } = React; function Timer({ setParentCounter }) { const [counter, setCounter] = React.useState(0); useEffect(() => { let countersystem; countersystem = setTimeout(() => setCounter(counter + 1), 1000); return () => { clearTimeout(countersystem); }; }, [counter]); return ( <div className="App"> <button onClick={() => { setParentCounter(counter); }} > Set parent counter value </button> <hr /> <div>Child Counter: {counter}</div> </div> ); } function App() { const [parentCounter, setParentCounter] = useState(0); return ( <div className="App"> Parent Counter: {parentCounter} <hr /> <Timer setParentCounter={setParentCounter} /> </div> ); } ReactDOM.render(<App />, document.getElementById('react-root')); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="react-root"></div>