Reactjs 为什么在本例中空字符串有效,但this.state.foo不';T
这是我的密码:Reactjs 为什么在本例中空字符串有效,但this.state.foo不';T,reactjs,boolean,jsx,Reactjs,Boolean,Jsx,这是我的密码: import React, { Component } from 'react' import classnames from 'classnames' class TodoTextInput extends Component { state = { text: this.props.text } handleSubmit = e => { const text = e.target.value.trim() if (e.which
import React, { Component } from 'react'
import classnames from 'classnames'
class TodoTextInput extends Component {
state = {
text: this.props.text
}
handleSubmit = e => {
const text = e.target.value.trim()
if (e.which === 13) {
this.props.onSave(text)
this.setState({
text: ''
})
}
}
handleChange = e => {
this.setState({
text: e.target.value
})
}
handleBlur = e => {
if (!this.props.newTodo) {
this.props.onSave(e.target.value)
}
}
render() {
return (
<input className={
classnames({
edit: this.props.editing,
'new-todo': this.props.newTodo
})
}
type='text'
autoFocus='true'
value={this.state.text}
onChange={this.handleChange}
placeholder={this.props.placeholder}
onKeyDown={this.handleSubmit} />
)
}
}
export default TodoTextInput
我有两个问题:
this.state.text
的初始值未定义(意思是this.props.text
未定义)。如果输入
的值
属性未定义,React将该输入视为“未控制”
在初始化状态中,应该返回空字符串
state = {
text: this.props.text || ''
}
要解决此问题,请向TodoTextInput
TodoTextInput.defaultProps = {
text: ''
}
TodoTextInput.defaultProps = {
text: ''
}