[react] 如何给非控组件设置默认的值?
<input defaultValue="123" />
<input name="username" type="text" value={this.state.username} onChange={this.handleChange} />
<input name="username" type="text" ref={username=>this.username=username}/>
给组件设置默认值,难道就没人说static defaultProps吗?
可在state设置默认值;
给非受控组件设置defaultValue属性,给定默认值
官方文档
示例代码:
import React from 'react'
export default class UnControlledComp extends React.Component {
constructor(props) {
super(props)
this.inputRef = React.createRef()
}
handleClick = () => {
console.log(this.inputRef.current.value);
}
render () {
return (
<>
<input defaultValue="default value" ref={this.inputRef}></input>
<button onClick={this.handleClick}>点击</button>
</>
)
}
}
Most helpful comment