[英]How to pass data from child component to parent component in reactjs
I am very new to React JS. 我是React JS的新手。 I am having a hard time understanding how to grab data from a component. 我很难理解如何从组件中获取数据。
I want to be able to grab the selected dates and output the date to the console, I am using react-datepicker 我希望能够获取所选日期并将日期输出到控制台,我正在使用react-datepicker
This is DateOptions.jsx 这是DateOptions.jsx
var DateOptions = React.createClass({
getInitialState: function() {
return {
startDate: moment(),
endDate: moment()
};
},
handleChangeStart: function(date) {
this.setState({
startDate: date
});
},
handleChangeEnd: function(date){
this.setState({
endDate: date
});
},
render: function() {
return (
<div>
<label>Start Date:</label>
<DatePicker
selected={this.state.startDate}
selectsStart startDate={this.state.startDate}
endDate={this.state.endDate}
onChange={this.handleChangeStart}
/>
<label>End Date:</label>
<DatePicker
selected={this.state.endDate}
selectsEnd startDate={this.state.startDate}
endDate={this.state.endDate}
onChange={this.handleChangeEnd}
/>
</div>
)
}
});
Then in my Main.jsx 然后在我的Main.jsx中
var Main = React.createClass({
render: function(){
return <DateOptions/>
}
})
Thanks very much for your help! 非常感谢您的帮助!
To get the Data from child component
, u need to use props
, props
are used to pass the data
or methods
from parent component
to child component
. 要从child component
获取数据,您需要使用props
, props
用于将data
或methods
从parent component
传递到child component
。
Step1: Pass a function from parent component to child component, like this: 第1步:将一个函数从父组件传递给子组件,如下所示:
var Main = React.createClass({
getData:function(data){
console.log(data);
},
render: function(){
return <DateOptions getData={this.getData}/>
}
})
Step2: In child component
use this method
to pass data back to parent component
, like this: 第2步:在child component
使用此method
将数据传递回parent component
,如下所示:
var DateOptions = React.createClass({
getInitialState: function() {
return {
date: moment()
};
},
handleChange: function(date) {
this.setState({
date: date
});
this.props.getData(date);
},
render: function() {
return (
<div>
<DatePicker
selected={this.state.date}
onChange={this.handleChange}
/>
</div>
)
}
});
Check the jsfiddle
for similar example for input element, u will get the idea how it works : https://jsfiddle.net/m933qjvk/ 检查jsfiddle
以获取输入元素的类似示例,您将了解其工作原理: https : jsfiddle
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.