我想将父组件中address
的更新状态传递给子组件的center
属性。更具体地说,从App组件到BaseMap组件。但是,我似乎无法使其发挥作用。可以帮助的新鲜的眼睛将不胜感激!
这是我的代码(我删除了fetch函数,它工作得很好,所以它不会打扰你。我只需要更新我的子组件的状态):
父:
class App extends Component {
constructor(props) {
super(props);
this.state = {
avatar: '',
username: 'nickname93',
realName: '',
location: '',
followers: '',
following: '',
repos: '',
address: ''
}
}
render() {
return (
<div>
<SearchBox fetchUser={this.fetchUser.bind(this)}/>
<Card data={this.state} />
<BaseMap center={this.state.address}/>
</div>
);
}
fetchApi(url) {
// some fetch functionality
}
fetchUser(username) {
let url = `https://api.github.com/users/${username}`;
this.fetchApi(url);
}
componentDidMount() {
let url = `https://api.github.com/users/${this.state.username}`;
this.fetchApi(url);
}
}
子组件:
export default class BaseMap extends React.Component {
constructor(props) {
super(props);
this.state = {
center: [24, 56],
zoom: 11
}
}
render() {
return (
<Col md={10} mdPull={1}>
<div className="map">
<GoogleMap
bootstrapURLKeys={'AIzaSyBhzwgQ3EfoIRYT70fbjrWASQVwO63MKu4'}
center={this.state.center}
zoom={this.props.zoom}>
</GoogleMap>
</div>
</Col>
);
}
}
答案 0 :(得分:3)
您的值正在从父组件App
传递到您的子组件BaseMap
。
您可以使用props
代替this.props.center
来访问或使用从父级传递给子组件的属性(也称为this.state.center
)。
export default class BaseMap extends React.Component {
constructor(props) {
super(props);
this.state = {
center: [24, 56],
zoom: 11
}
}
render() {
return (
<Col md={10} mdPull={1}>
<div className="map">
<GoogleMap
bootstrapURLKeys={'AIzaSyBhzwgQ3EfoIRYT70fbjrWASQVwO63MKu4'}
center={this.state.center} // this is [24,56]
centerFromParentComponent = {this.props.center} // this is the property passed from parent component
zoom={this.props.zoom}>
</GoogleMap>
</div>
</Col>
);
}
}
使用this.props
,您可以访问从父组件传递的任何属性(例如状态,变量或方法)。
您可能还想查看componentWillReceiveProps()方法。你可能很快就会有需要。
答案 1 :(得分:1)
如果您希望 function dates_between($startdate, $enddate, $format=null){
(is_int($startdate)) ? 1 : $startdate = strtotime($startdate);
(is_int($enddate)) ? 1 : $enddate = strtotime($enddate);
if($startdate > $enddate){
return false; //The end date is before start date
}
while($startdate < $enddate){
$arr[] = ($format) ? date($format, $startdate) : $startdate;
$startdate += 86400;
}
$arr[] = ($format) ? date($format, $enddate) : $enddate;
return $arr;
}
$fecha1 = $from;
$fecha2 = $until;
$data = dates_between($fecha1, $fecha2, 'Y-m-d');
foreach ($data as $cal_date) {
$sql = $dbh->prepare ("insert into table.`$property`(cal_date)" ."VALUES (:cal_date)");$sql->execute(array('cal_date' => $cal_date));}
从父this.props.center
接收状态更新,请使用this.state.center
代替BaseMap
。您似乎想要为App
道具设置默认值。这是the doc声明默认道具。