P粉6524951942023-08-28 09:50:36
Pass data from child component to parent component
In parent component:
getData(val){ // do not forget to bind getData in constructor console.log(val); } render(){ return(<Child sendData={this.getData}/>); }
In child components:
demoMethod(){ this.props.sendData(value); }
P粉9464374742023-08-28 00:20:33
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 DropdownList
valueField
and textField
properties
Short answer
Father:
<div className="col-sm-9"> <SelectLanguage onSelectLanguage={this.handleLanguage} /> </div>
child:
handleLangChange = () => { var lang = this.dropdown.value; this.props.onSelectLanguage(lang); }
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 this
Father
class ParentComponent extends React.Component { state = { language: '' } handleLanguage = (langValue) => { this.setState({language: langValue}); } render() { return ( <div className="col-sm-9"> <SelectLanguage onSelectLanguage={this.handleLanguage} /> </div> ) } }
child
var json = require("json!../languages.json"); var jsonArray = json.languages; export class SelectLanguage extends React.Component { state = { selectedCode: '', selectedLanguage: jsonArray[0], } handleLangChange = () => { var lang = this.dropdown.value; this.props.onSelectLanguage(lang); } render() { return ( <div> <DropdownList ref={(ref) => this.dropdown = ref} data={jsonArray} valueField='lang' textField='lang' caseSensitive={false} minLength={3} filter='contains' onChange={this.handleLangChange} /> </div> ); } }
Use the createClass
syntax that the OP used in his answer
Father
const ParentComponent = React.createClass({ getInitialState() { return { language: '', }; }, handleLanguage: function(langValue) { this.setState({language: langValue}); }, render() { return ( <div className="col-sm-9"> <SelectLanguage onSelectLanguage={this.handleLanguage} /> </div> ); });
child
var json = require("json!../languages.json"); var jsonArray = json.languages; export const SelectLanguage = React.createClass({ getInitialState: function() { return { selectedCode: '', selectedLanguage: jsonArray[0], }; }, handleLangChange: function () { var lang = this.refs.dropdown.value; this.props.onSelectLanguage(lang); }, render() { return ( <div> <DropdownList ref='dropdown' data={jsonArray} valueField='lang' textField='lang' caseSensitive={false} minLength={3} filter='contains' onChange={this.handleLangChange} /> </div> ); } });
JSON:
{ "languages":[ { "code": "aaa", "lang": "english" }, { "code": "aab", "lang": "Swedish" }, ] }