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