0

我打算用 React 添加一个预填充的表单。我有关于道具的实际数据。这就是我想出的。

@connect(...)
class Some extends React.Component {
   state = {
      ...this.props.auth.user
   }

   render() {
     // Create a form using the data on state
   }
}

它看起来不正确,因为我在这里没有使用反应生命周期钩子。我想问是否有更好的做法来实现我想要做的事情。

4

2 回答 2

2

我不确定你的架构,因为你在这里使用不受控制的组件,建议将真相的来源保存在一个地方。

你可以这样做:

@connect(...)
class Some extends React.Component {
constructor(props) {
    super(props);
    this.state = {
      userName:this.props.auth.user
   }
}
handleChange = (event) => {
    this.setState({userName: event.target.value});
  }

   render() {
      return(
         <div>
          <input onChange={this.handleChange} id="some" type="text" value= {this.state.userName}/>
        </div>
     )
   }
}

如果您想使用通过父/容器控制的受控组件。您可以通过道具管理值并设置道具onChange。

于 2020-06-01T11:14:08.093 回答
1

因此,要详细说明我之前的回复,您将执行以下操作来实现您想要的:

@connect(...)
class Some extends React.Component {
constructor(props) {
    super(props);
    this.state = {
      value: '',
   }
}
handleChange = (event) => {
    this.setState({ value: event.target.value });
  }

   render() {
      return(
         <div>
          <input onChange={this.handleChange} id="some" type="text" value= {this.state.value|| this.props.value}/>
        </div>
     )
   }
}

虽然您的值是一个空字符串(在该州),但这些字段将从您的道具中填充,并且一旦您开始输入,它将用您所在州的值覆盖预填充的值。

最佳实践是实际拥有一个处理此逻辑的组件,然后将道具传递给应该只是一个愚蠢的演示组件的表单:

class SomeController extends React.Component {
 constructor(props) {
    super(props);
    this.state = {
      value: '',
    }
 }
 handleChange = (event) => {
    this.setState({ value: event.target.value });
  }

  return (<Form handleChange={this.handleChange} value={this.state.value} />)
}

然后你的表单组件:

const Form = (props) => (
  <form>
    <input onChange={props.handleChange} value={props.value} />
  </form>
);

希望这个解释有所帮助。

于 2020-06-01T12:29:06.750 回答