首页 > 解决方案 > Invariant Violation:对象作为 React 子级无效(React Native)

问题描述

我正在尝试实现一个简单的功能,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)

我是新来的本地人,所以我对此一无所知。

标签: javascriptreactjsreact-native

解决方案


在您<TextInput>使用的是onChange道具而​​不是onChangeText,因此您尝试在<Text>. 只需更改该道具,它应该可以工作

  <TextInput
    style={styles.placeInput}
    value={this.state.textInput}
    placeholder="enter anything"
    onChangeText={this.onChangeName}
  />

另请注意,您正在复制其style属性。统一它们或将它们作为数组传递

style={[styles.placeInput, {width: 300}]}

推荐阅读