【问题标题】:Get input Data from child component React从子组件 React 获取输入数据
【发布时间】:2021-03-04 00:18:03
【问题描述】:

我有一个 React 表单,但是,我不使用表单的 Input,而是尝试将其替换为名为 SearchInput 的组件。该组件返回一个选择并带有以下道具:

render() {
    const options = this.state.data.map(d => <Option key={d.value}>{d.text}</Option>);
    return (
      <Select
        showSearch
        value={this.state.value}
        placeholder={this.props.placeholder}
        style={this.props.style}
        defaultActiveFirstOption={false}
        showArrow={false}
        filterOption={false}
        onSearch={this.handleSearch}
        onChange={this.handleChange}
        notFoundContent={null}
      >
        {options}
      </Select>
    );
  }

我是 React 的超级新手。所以我试图做某事。像这样

class CityForm extends React.Component {
render() {
    return (
      <Form onFinish={this.onFinish} >
        <SearchInput value={this.state.value} style={{ width: 200 }} />
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
       </Form>
    );
  }
}

基本上只是将我的 SearchInput 渲染到 CityForm 中。但是我意识到,当然,表单并没有真正理解我的选择,因为它是输入。因此,我无法真正从中获得任何价值以进行进一步的搜索提交。有没有办法将我的选择直接呈现到表单的输入中并将其值作为数据获取,可以继续进行搜索(在提交时)?

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

    我可以自己找到这个。只需在我的子组件中更改以下内容:

    value={this.props.value}
    onChange={this.props.onChangeValue}
    

    并将我的表单组件中的属性更改为

    <SearchInput value={this.state.value} onChangeValue={this.handleChangeValue} style={{ width: 200 }} />
    

    我能够设置默认值并跟随值的变化。不过这篇文章非常有帮助。 React - Can A Child Component Send Value Back To Parent Form

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-19
      • 2021-06-11
      • 1970-01-01
      • 2019-11-22
      • 2018-02-27
      • 1970-01-01
      • 2023-03-25
      相关资源
      最近更新 更多