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

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

当前回答

将数据从子组件传递给父组件

在父组件中:

getData(val){
    // do not forget to bind getData in constructor
    console.log(val);
}
render(){
 return(<Child sendData={this.getData}/>);
}

在子组件中:

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

其他回答

将数据从子组件传递给父组件

在父组件中:

getData(val){
    // do not forget to bind getData in constructor
    console.log(val);
}
render(){
 return(<Child sendData={this.getData}/>);
}

在子组件中:

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

我发现了如何从父母中的子组件中获取数据的方法,当我需要它时。

家长:

class ParentComponent extends Component{
  onSubmit(data) {
    let mapPoint = this.getMapPoint();
  }

  render(){
    return (
      <form onSubmit={this.onSubmit.bind(this)}>
        <ChildComponent getCurrentPoint={getMapPoint => {this.getMapPoint = getMapPoint}} />
        <input type="submit" value="Submit" />
      </form>
    )
  }
}

孩子:

class ChildComponent extends Component{
  constructor(props){
    super(props);

    if (props.getCurrentPoint){
      props.getCurrentPoint(this.getMapPoint.bind(this));
    }
  }

  getMapPoint(){
    return this.Point;
  }
}

这个例子展示了如何将函数从子组件传递给父组件,并使用该函数从子组件获取数据。

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

父组件

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

我希望这能起作用

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

在React钩子中父组件和子组件之间传递数据

将函数传递给子函数, 并通过调用父函数来等待子函数返回值

父母(. . / app.js)

import MyCOMP from "../component/MyCOMP"; //import child component

export default function MyMainPage() {
return(
  <>
    <MyCOMP 
      //pass function to child and wait child passback the changed value
      // 1.Click child component passing function to child

    ParentFunction={(x)=>{
      console.log('Child Pass Back Value',x)  

      // 3. Parent received data
      // after you get the value change you can ultilize another function, useEffect or useState 
    }}/>
  </>
)
}

孩子(. . /组件/ MyCOMP.js)

export default function MyCOMP({ParentFunction}){
  return(
    <>
      <button onClick={()=>{ 

        // 2. Child passing back value to parent 
        ParentFunction("Child reply ANSWER is ","fm 99.8");}}>Click Me</button>

    </>
  )
}

结果

点击按钮后,父类显示“fm99.8”的sting值(该 孩子的价值)

请在下面评论,如果这对你有帮助,或者你有其他的想法