【发布时间】:2017-06-10 18:06:46
【问题描述】:
我正在构建一个 React Native 应用程序,但我遇到了这个问题,我不知道如何解决
在我的屏幕上,我有一个开关,按下时会调用一个函数:
function RoundTrip(props) {
console.log('value of round trip' + props.returnBool)
var roundTrip = props.returnBool;
if (roundTrip) {
console.log('return is true')
return <RoundTripTrue />;
}
console.log('return is false')
return <RoundTripFalse />;
}
function RoundTripFalse(props) {
return null
}
function RoundTripTrue(props) {
return (
<View>
<CardSectionInput>
<Image
source={require('./../../src/images/dateIcon1.png')}
style={styles.IconStyle}
/>
<DatePicker
style={styles.DateStyle}
date={this.state.returnDate}
mode='date'
format="LL"
minDate= {currentDate}
maxDate="2018-06-01"
confirmBtnText="Confirm"
cancelBtnText="Cancel"
showIcon={false}
placeholder= 'Return Date'
customStyles={{
dateInput: {
marginLeft: 2,
backgroundColor: 'white',
borderWidth: 1,
borderRadius: 5,
borderColor: 'white',
flex: 1,
flexDirection: 'row',
},
dateText: {
flexDirection: 'row',
flex: 1,
backgroundColor: 'transparent',
color: 'black',
},
placeholderText: {
color: '#c9c9c9',
alignSelf: 'center',
justifyContent: 'flex-start',
flex: 1,
flexDirection: 'row',
fontSize: 18,
}
}}
onDateChange={(returnDate) => {this.setState({returnDate: returnDate})}}
/>
</CardSectionInput>
<CardSectionInput>
<Image
source={require('./../../src/images/timeIcon.png')}
style={styles.TimeIconStyle}/>
<DatePicker
style={styles.DateStyle}
date={this.state.returnTime}
mode="time"
format="LT"
confirmBtnText="Confirm"
cancelBtnText="Cancel"
minuteInterval={20}
showIcon={false}
placeholder='Return Time'
onDateChange={(returnTime) => {this.setState({returnTime: returnTime});}}
customStyles={{
dateInput: {
marginLeft: 2,
backgroundColor: 'white',
borderWidth: 1,
borderRadius: 5,
borderColor: 'white',
flex: 1,
flexDirection: 'row',
},
dateText: {
flexDirection: 'row',
flex: 1,
backgroundColor: 'transparent',
color: 'black',
},
dateTouchBody: {
flexDirection: 'row',
height: 40,
alignItems: 'center',
justifyContent: 'center',
flex: 1,
paddingTop: 5,
},
placeholderText: {
color: '#c9c9c9',
alignSelf: 'center',
justifyContent: 'flex-start',
flex: 1,
flexDirection: 'row',
fontSize: 18,
}
}}
/>
</CardSectionInput>
这工作正常,但是当我尝试将 RoundTrip 函数的状态更改为我的父级时出现问题。
在我的父母中,我打电话给<RoundTrip returnBool={this.state.roundTrip} />
我知道我的函数无法访问我父母的状态,但我不知道如何解决这个问题。
此问题并非特定于我的 RoundTrip 函数,因为每当我尝试将文件分成组件时都会遇到此问题。
提前谢谢你
【问题讨论】:
-
所以问题是当您将这些函数放入不同的文件时?为什么不把
export和import放在一个新文件中呢?也为了返回父级,只需传递一个函数<RoundTrip onSelectionChange={this.handleChange} />其中handleChange 是一个接受一些值并设置状态的函数。 -
另外,这里的示例称为
Functional Components,而不是React Class。功能组件没有状态,您不能在其中调用 setstate。这应该引发异常。如果你想使用状态,你需要让这些反应类与状态
标签: javascript reactjs react-native native