[英]Passing props between components in react native
我有一個名為 DatePickerComponent.js 的組件
import React, { Component } from 'react'; import {DatePicker} from 'native-base'; export default class DatePickerComponent extends Component { constructor(props) { super(props); this.state = { chosenDate: new Date() }; this.setDate = this.setDate.bind(this); } render() { return ( <DatePicker defaultDate={new Date()} minimumDate={new Date()} onDateChange={this.setDate} />) } }
我在 Parent.js 組件中導入 DatePicker 組件,並且還需要 DatePicker 組件中的值更改。 如何使用道具獲取值?
import React, {Component} from 'react'; import DatePickerComponent from '../../components/DatePicker'; export default class Parent extends Component { constructor(props) { super(props); } render() {return (<DatePickerComponent/>)} }
您需要將 dateChangeHandler function 作為來自父組件的 prop 傳遞。
import React, {Component} from 'react';
import DatePickerComponent from '../../components/DatePicker';
export default class Parent extends Component {
constructor(props) {
super(props);
}
handleDateChanges(date){
console.log(date);
}
render() {
return (
<DatePickerComponent
onDateChange={this.handleDateChange}
/>
)
}
}
DatePicker 有一個onDateChange
事件,該事件在其爭論中提供date
,因此子組件可以更新為:
import React, { Component } from 'react';
import {DatePicker} from 'native-base';
export default class DatePickerComponent extends Component {
constructor(props) {
super(props);
this.state = { chosenDate: new Date() };
// this.setDate = this.props.onDateChange.bind(this);
}
handleDateChange(date){
this.props.onDateChange(date);
}
render() {
return (
<DatePicker
defaultDate={new Date()}
minimumDate={new Date()}
onDateChange={(date) => this.handleDateChange(date)}
/>
)
}
}
對我來說,它的工作原理是這樣的:
import React, { Component } from 'react';
import {DatePicker} from 'native-base';
export default class DatePickerComponent extends Component {
constructor(props) {
super(props);
this.state = {
chosenDate: new Date()
};
this.handleDateChange = this.handleDateChange.bind(this);
}
handleDateChange = (itemValue, itemIndex) => {
//send state to parent if needed
this.props.handleDate(itemValue);
this.setState({chosenDate: itemValue})
}
render() {
return (
<DatePicker
date={this.state.chosenDate}
//defaultDate={new Date()}
//minimumDate={new Date()}
onDateChange={this.handleDateChange}
/>
)
}
}
父組件
import React, {Component} from 'react';
import DatePickerComponent from '../../components/DatePicker';
export default class Parent extends Component {
constructor(props) {
super(props);
this.state = {
date: new Date(),
}
handleDate = (itemValue) => {
this.setState({date: itemValue});
}
}
render() {
return (
<DatePickerComponent
handleDate={this.handleDate}
/>
)}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.