在流星中react不工作的defaultValue

defaultValue of react not working in meteor

本文关键字:工作 defaultValue react 流星      更新时间:2023-09-26

我正在努力解决这个问题,我不知道为什么不起作用

<input type="text" id="first_name" name="first_name" className="form-control" defaultValue={this.props.user.first_name}  required/>

但这对有效

<input type="text" id="first_name" name="first_name" className="form-control" value={this.props.user.first_name}  required/>

区别是valuedefaultValue,如果我使用值,字段将变为只读,并且使用defaultValue不会打印任何内容。

我正在用流星反应。在return语句之前,我曾尝试在render方法中记录this.props.user,它会打印对象。

当您将this.props.user.first_name分配给value属性时,并不是输入字段变为只读,而是您永远不会处理该值更改时发生的情况。React只是用每次直接分配给它的值重新渲染它。

如果您希望使字段可编辑+具有默认用户名值,则可能需要维护并了解输入的状态。

例如:

// Initialize some component state in either your constructor or getInitialState function
constructor(props){
  super(props);    
  this.state = {userInput: this.props.user.first_name};
}

// Have a function that updates state when your input changes
onInputChange(event) {
  this.setState({ userInput: event.target.value });
}

// Then set the value equal to your userInput state and add an onChange 
// prop to the input tag in your render method.
render() {
  return (
  ...
  <input 
    type="text" 
    id="first_name" 
    name="first_name" 
    className="form-control" 
    value={this.state.userInput}
    onChange={this.onInputChange.bind(this)} />
  )
} 

然后,字段的值初始化为通过this.props.user.first_name提供的值,同时保持可编辑状态。

编辑:

正如评论中所指出的,虽然这是有效的,但这实际上是React中的一种反模式。因为子组件的初始状态只调用一次,所以从父组件更改为this.props.user.first_name的prop值不会导致子组件的状态发生任何更改。如果用例是明确地设置一个初始值,而您不希望或期望在组件生命周期中更改该初始值(尽管即使在那时,这也不是一个好的模式),那么这是可以的,但如果您确实期望初始值是可变的,那么您有两种选择。

选项一:将状态带入父组件,它可能属于该组件。然后,子组件应该接收并呈现按其方式发送的任何道具。对初始值的更改在父组件状态下处理,道具被视为不可变的,并且一切保持同步。

选项二:如果出于任何原因,您都需要从道具中确定状态,并且您也希望这些道具发生变化,那么您可以使用componentWillReceiveProps(nextProps)生命周期方法来保持一切同步。这将允许您对照nextProps检查this.props,并在必要时进行任何状态更改:

componentWillReceiveProps(nextProps) {
  if(nextProps.user.first_name !== this.props.user.first_name){
    this.setState({
      userInput: nextProps.user.first_name
    });
  }
}

以下是DOCS的链接以供进一步参考。