给出下面的组件,我无法键入TextInput
,然后写信然后删除,这似乎是在更新状态。有任何线索吗?
class myContainerComponent extends Component {
constructor(props) {
super(props)
this.onChange = this.onChange.bind(this)
}
onChange(value) {
this.setState({
value
})
}
render() {
return (
<PresentationalComponent
onChange={this.onChange}
value={this.state.value}
/>
)
}
}
class PresentationalComponent extends Component {
render() {
return(
<TextInput
onChangeText={this.props.onChange}
value={this.props.value}
/>
)
}
}
有任何线索吗?
答案 0 :(得分:2)
将此添加到您的 myContainerComponent 构造函数中:
this.state = {
value: '',
}
答案 1 :(得分:2)
您应该在构造函数中初始化状态:
constructor(props){
super(props);
this.state = {
value: ''
}
}
答案 2 :(得分:1)
import * as React from 'react';
import { TextInput } from 'react-native';
export default class App extends React.Component {
constructor(props) {
super(props)
this.state = {
value: {}
};
this.onChange = this.onChange.bind(this)
}
onChange(value) {
this.setState({
value
})
}
render() {
return (
<PresentationalComponent
onChange={this.onChange}
value={this.state.value}
/>
)
}
}
class PresentationalComponent extends React.Component {
render() {
return(
<TextInput
onChangeText={this.props.onChange}
value={this.props.value}
/>
)}
}
答案 3 :(得分:1)
我相信其他两个答案都是正确的,但是您可以进一步简化代码,并使用箭头函数摆脱构造函数的声明:
class myContainerComponent extends Component {
state = {
value: ''
}
onChange = (value) => {
this.setState({
value
})
}
render() {
return (
<PresentationalComponent
onChange={this.onChange}
value={this.state.value}
/>
)
}
}