【问题标题】:React Access Value in Functional Component from Class Component从类组件中反应功能组件中的访问值
【发布时间】:2021-12-12 20:08:54
【问题描述】:

我正在使用一个名为 react-semantic-ui-datepickers 的 React 模块,我相信它基于 react-datepicker。无论哪种方式,这更像是一个通用的 React 问题。我在同一个文件中有我的主类组件和日期选择器功能组件。日期选择器呈现并正常工作,但我无法弄清楚 如何 访问主类组件中日期选择器的实际值。

代码的简化版本如下所示,我只是在控制台中注销了一些变量的值。谁能给我一个关于从类组件访问所选日期选择器值的最佳方法的建议?

import Layout from '../../components/Layout';
import React, { Component, useState } from 'react';
import SemanticDatepicker from 'react-semantic-ui-datepickers';
import { Message, Form, Icon, Button, Input } from 'semantic-ui-react';
import 'react-semantic-ui-datepickers/dist/react-semantic-ui-datepickers.css';

class MyForm extends Component {
  state = {
    colour: 'Black',
    description: ''
  };

  onSubmit = async (event) => {
    event.preventDefault();

    console.log(this.state.colour); // Shows current colour field value.
    console.log(this.state.description); // Shows current description field value.
    console.log(); // How do I access the selected value of the date picker field??
  };

  render()  {
    return (
      <Layout>
        <Form onSubmit={this.onSubmit}>
          <Form.Field>
            <Form.Group>
            <Form.Field control='select' value={this.state.colour} onChange={event => this.setState({ colour: event.target.value })}>
              <option value='Black'>Black</option>
              <option value='Blue'>Blue</option>
              <option value='Green'>Green</option>
              <option value='Orange'>Orange</option>
            </Form.Field>
            <DatePicker />
            </Form.Group>
            <label>Description</label>
            <Form.TextArea value={this.state.description} onChange={event => this.setState({ description: event.target.value })} />
          </Form.Field>
          <Button icon='add' labelPosition='left' content='Add' primary />
        </Form>
      </Layout>
    );
  }
}

const DatePicker = () => {
  const [endDate, setNewDate] = useState(null);
  const onChange = (event, data) => setNewDate(data.value);

  return <SemanticDatepicker onChange={onChange} />;
};

export default MyForm;

【问题讨论】:

标签: reactjs react-hooks next.js react-functional-component


【解决方案1】:

您需要将日期选择器的状态“提升”到您需要的位置,即MyForm 组件中。

然后MyForm 组件应该将onChange 处理程序作为道具传递给DatePicker 组件,然后将其传递给SemanticDatePicker — 作为旁注,您可能不需要DatePicker 组件不再存在,因为它变成了 SemanticDatePicker 的空包装器。不管怎样,当SemanticDatePicker调用onChange处理程序时,它实际上会写入MyForm级别声明的状态,然后您可以在MyForm的方法中安全地读取它。

React 官方文档中的 Lifting State Up 部分正在解决这个特定的用例。

【讨论】:

  • 感谢您的帮助,迈克尔。我现在已经阅读了关于提升状态的各种文章,这绝对是我所追求的。我理解这个概念,但由于某种原因,它似乎仍然无法在我的代码中真正发挥作用。
猜你喜欢
  • 1970-01-01
  • 2022-11-21
  • 2020-08-12
  • 2021-05-25
  • 1970-01-01
  • 1970-01-01
  • 2019-10-09
  • 2019-12-29
  • 1970-01-01
相关资源
最近更新 更多