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

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

当前回答

 import { useEffect, useState } from "react";
  
  export default function App() {
    const data = (data) => {
      console.log("data", data);
    };
  
    const myData = {
      name: "hi this is my data"
    };
  
    return <Form onSubmit={data} myDatasa={myData} />;
  }
  
  const Form = (props) => {
    console.log("myData", props.myDatasa.name);
  
    const [choreDesc, setChoreDesc] = useState();
    const handleSubmit = (e) => {
      e.preventDefault();
      props.onSubmit(choreDesc);
    };
  
    const handlechange = (e) => {
      setChoreDesc(e.target.value);
    };
  
    return (
      <form
        onSubmit={(e) => {
          handleSubmit(e);
        }}
      >
        <label>Chore description:</label>
        <br />
        <input
          name="choreDesc"
          type="text"
          value={choreDesc}
          onChange={handlechange}
        />
        <br />
        <input type="submit" value="Add Log" />
      </form>
    );
  };
  ```

其他回答

最近我发现了一种很好的方法。

本质上,我只是useState,然后设置onChange作为孩子的道具,它将“value”作为参数,并将其放入useState“setVal”,boom,我得到状态改变child ->父母每次

const Parent = () => {
  const [val, setVal] = useState("initial value")
  return(
    <>
    <Child onChange={(value)=> setVal(value)}/>
    <div>{val}</div>
    </>
  )
};

export default Parent;

const Child = (props) => {
  return(
  <button onClick={() => props.onChange("your value here") }>
  )
}

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

}

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

你传递了一个错误的函数给子组件,并且你的父类没有handllanguage函数。你可以这样传递:<SelectLanguage onSelectLanguage={this. handlelanguagechange}/>。我认为如果一个函数在类中不存在,它将是None。 你的父组件应该是这样的:

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

您可以使用useState在ParentComponent中创建状态,并将setIsParentData函数作为道具传递到ChildComponent中。

在ChildComponent中,通过prop使用接收函数更新数据,将数据发送回ParentComponent。

我使用这种技术,特别是当我在ParentComponent中的代码太长时,因此我将从ParentComponent创建子组件。通常情况下,它只会向下1级,为了在组件之间共享状态,使用useContext或redux似乎有些过度。

ParentComponent.js

import React, { useState } from 'react';
import ChildComponent from './ChildComponent';

export function ParentComponent(){
  const [isParentData, setIsParentData] = useState(True);

  return (
    <p>is this a parent data?: {isParentData}</p>
    <ChildComponent toChild={isParentData} sendToParent={setIsParentData} />
  );
}

ChildComponent.js

import React from 'react';

export function ChildComponent(props){

  return (
    <button onClick={() => {props.sendToParent(False)}}>Update</button>
    <p>The state of isParentData is {props.toChild}</p>
  );
};