我正在尝试实现一个简单的功能,按钮的onPress
应该添加placeName
来放置数组并将其显示在视图中,但似乎出现错误,请帮忙>
这是我的代码,
export default class App extends Component{
state = {
placeName: "",
places: []
}
onChangeName = (val) => {
this.setState({
placeName: val
})
}
placeSubmitHandler = () => {
if(this.state.placeName === "") {
alert('enter something');
} else {
this.setState(prevState => {
return {
places: prevState.places.concat(prevState.placeName)
}
})
}
}
render() {
const placesOutput = this.state.places.map((place, i) => (
<Text key={i}>{place}</Text>
));
return (
<View style={styles.container}>
<View style={styles.inputContainer}>
<TextInput
style={{width: 300}}
value={this.state.textInput}
placeholder='enter anything'
onChange={this.onChangeName}
style={styles.placeInput}
/>
<Button title='Add' style={styles.placeButton} onPress={this.placeSubmitHandler}/>
</View>
<View>
{placesOutput}
</View>
</View>
);
}
}
这是错误消息,
Invariant Violation: Objects are not valid as a React child (found: object with keys {dispatchConfig, _targetInst, _dispatchListeners, _dispatchInstances, type, target, currentTarget, eventPhase, bubbles, cancelable, timeStamp, defaultPrevented, isTrusted, nativeEvent, isDefaultPrevented, isPropagationStopped}). If you meant to render a collection of children, use an array instead.
in RCTText (at Text.js:154)
in TouchableText (at Text.js:278)
in Text (at App.js:48)
in RCTView (at View.js:45)
in View (at App.js:62)
in RCTView (at View.js:45)
in View (at App.js:51)
in App (at renderApplication.js:35)
in RCTView (at View.js:45)
in View (at AppContainer.js:98)
in RCTView (at View.js:45)
in View (at AppContainer.js:115)
in AppContainer (at renderApplication.js:34)
我是新来的本地人,所以我对此一无所知。
答案 0 :(得分:2)
在您的<TextInput>
中,您使用的是onChange
道具而不是onChangeText
,以便尝试在<Text>
中渲染对象。只需更改该道具即可使用
<TextInput
style={styles.placeInput}
value={this.state.textInput}
placeholder="enter anything"
onChangeText={this.onChangeName}
/>
还要注意,您正在复制其style
属性。统一它们或将它们作为数组传递
style={[styles.placeInput, {width: 300}]}
答案 1 :(得分:0)
您的placesOutput变量返回的对象为jsx。
代替
const placesOutput = this.state.places.map((place, i) => (
<Text key={i}>{place}</Text>
));
尝试
const placesOutput = this.state.places.map((place, i) => (
<Text key={i}>{place.name} /* place is an object use any property of it. */</Text>
));