通过输入设置组件中的状态

时间:2018-09-12 22:30:35

标签: javascript reactjs react-native

我试图在组件中设置输入的状态,并在我的app.js中使用它。我怎样才能用道具做到这一点?我尝试过onChangeText={(tips) => this.setState({comment})},但是我却没有定义。.

const Comments = (props) => {
  return (
    <View style={styles.container}>
<Input style={styles.field}
  autoCorrect={false}
  autoCapitalize="none"
  onChangeText={props.onChangeText}
  placeholder="Skriv en kommentar..."
/>
<Button rounded style={styles.button} onPress={() => props.addComment(props.id)}>
  <Text style={styles.buttonText}>Kommenter</Text>
</Button>
</View>
  )
}
export { Comments };

在我的app.js中,我有:

我的app.js

    export default class Home extends Component {
    constructor(props){
    super(props);
    this.state = {
      comment: '',
    }
   newComment = (comment) => {
      change = (comment) => this.setState(comment)
      alert(comment)
   }
  renderItem = ({ item, index }) => {
   return (
       <Comments
          addComment={this.newComment}
          comments={this.state.comment}
          onChangeText={this.change}
        />
   )
  }
 }

2 个答案:

答案 0 :(得分:1)

假设您有一个父组件< MyContainer/>和一个标准< Input/>组件。使用输入的初始值设置父级的状态。像这样:

class MyContainer extends Component{
    state ={ value: '' }

    onChangeTextHandler = e =>{
        this.setState({value: e.target.value})
    }
}

现在,只需通过道具将对这个函数的引用传递给您的< Input/>组件: < Input onChangeText={this.onChangeTextHandler} value={this.state.value}/>

深入了解Two-way data binding

答案 1 :(得分:1)

您不能在无状态组件中使用cProfile。 您需要从父函数传递一个setState,该父函数根据handler

来更改值

父母

onChangeText

孩子

change = (comment) => this.setState({comment})

<Comments
   comments={this.state.comment}
   onChangeText={this.change}
/>