P粉6524951942023-08-28 09:50:36
将数据从子组件传递到父组件
在父组件中:
getData(val){ // do not forget to bind getData in constructor console.log(val); } render(){ return(<Child sendData={this.getData}/>); }
在子组件中:
demoMethod(){ this.props.sendData(value); }
P粉9464374742023-08-28 00:20:33
这应该有效。在发送回 prop 时,您将其作为对象发送,而不是将其作为值发送,或者将其用作父组件中的对象。其次,您需要格式化 json 对象以包含名称值对,并使用 DropdownList
valueField
和 textField
属性
简答
父级:
<div className="col-sm-9"> <SelectLanguage onSelectLanguage={this.handleLanguage} /> </div>
孩子:
handleLangChange = () => { var lang = this.dropdown.value; this.props.onSelectLanguage(lang); }
详细:
编辑:
考虑到 React.createClass 从 v16.0 开始已被弃用,最好通过扩展 React.Component
来创建 React 组件。使用此语法将数据从子组件传递到父组件将如下所示
父级
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> ) } }
孩子
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> ); } }
使用OP在其答案中使用的createClass
语法
父级
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> ); });
孩子
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" }, ] }