How to pass data from child component to parent component in ReactJS?
P粉441076405
2023-08-27 13:34:07
<p>I'm trying to send data from a child component to its parent component like this: </p>
<pre class="brush:php;toolbar:false;">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>
);
});</pre>
<p>This is the subcomponent:</p>
<pre class="brush:php;toolbar:false;">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>
);
}
});</pre>
<p>What I need is to get the user selected value in the parent component. I get this error: </p>
<pre class="brush:php;toolbar:false;">Uncaught TypeError: this.props.onSelectLanguage is not a function</pre>
<p>Can anyone help me figure out the problem? </p>
<p>P.S. subcomponent is creating a dropdown from a json file, I need the dropdown to display two elements of a json array next to each other (eg: "aaa,english" as preferred!)</p>
<pre class="brush:php;toolbar:false;">{
"languages":[
[
"aaa",
"english"
],
[
"aab",
"swedish"
],
}</pre>
<p><br /></p>
Pass data from child component to parent component
In parent component:
In child components:
This should work. When sending the prop back, you are sending it as an object instead of sending it as a value or using it as an object in the parent component. Second, you need to format the json object to contain name value pairs and use the
'sDropdownList
valueField
andtextField
propertiesShort answer
Father:
child:
detailed:
edit:
Considering that React.createClass has been deprecated since v16.0, it is best to create React components by extending
React.Component
. Passing data from child component to parent component using this syntax will look like thisFather
child
Use the
createClass
syntax that the OP used in his answer Fatherchild
JSON: