【问题标题】:In JSX | React How can the prop be passed to the button state so the button state can load a new page?在 JSX | React 如何将 prop 传递给按钮状态,以便按钮状态可以加载新页面?
【发布时间】:2019-10-15 07:17:38
【问题描述】:

尝试使用反应日期选择器从搜索中退出,然后检查可用日期。在将道具传递给 btn 时遇到了一些问题,因此我可以根据所选日期创建新页面。

一切都正确导入,我们可以在下面省略我的 Datapicker 组件和我需要使用 pop 的 Btnsearch 组件。

我尝试在组件的每个元素中传递道具,并将 btn 内置到组件中。我已经阅读了将道具传递到元素链中的更好方法。对于孩子们,所以我最后尝试这样做。似乎仍然无法捕捉到 Datepicked 甚至 console.log 它。也尝试构建警报。


class Datepicker extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ""
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleChange(event) {
    this.setState({ value: event.target.value });
  }

  handleSubmit(event) {
    alert("A name was submitted: " + this.state.value);
    event.preventDefault();
  }
  state = {};
  render() {
    console.log(this.props.value);
    return (
      <>
        <FormGroup>
          <InputGroup className="input-group-alternative">
            <InputGroupAddon addonType="prepend">
              <InputGroupText
              >
                <i className="ni ni-calendar-grid-58" />
              </InputGroupText>
            </InputGroupAddon>
            <ReactDatetime
            value={this.state.value}
            onChange={this.handleChange}
            inputProps={{
              placeholder: "Date Picker Here"
            }}
            timeFormat={false}
            />
          </InputGroup>
        </FormGroup>
        <Btnsearch />
      </>
    );
  }
}

export default Datepicker;

class Btnsearch extends React.Component {
    render() {
        return (
        <button value={this.props.value} className="btn btn-success search-card-btn">Search</button>
    );
    }
};

export default Btnsearch;

我希望 console.log 并在单击按钮时提醒道具已更改以填充新页面。我得到未定义的道具

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    只需传递道具:

     <Btnsearch value={this.state.value}/>
    

    否则你的组件永远不会得到它。

    编辑:你的代码有几个问题,我做了一个sn-p给你检查。

    https://stackblitz.com/edit/react-af37vl

    选择一个日期,点击“搜索”,日期将记录在控制台中。

    通知(来自 react-datetime 文档):

    日期更改时的回调触发。回调接收 选择时刻对象作为唯一参数,如果输入中的日期是 有效的。如果输入中的日期无效,则回调接收 输入的值(字符串)。

    【讨论】:

    • 当然这是一个有效的观点,但这并不能解决 Prop 甚至不会得到 console.loged 的​​事实
    • × TypeError: Cannot read property 'value' of undefined Datepicker.handleChange src/components/Toolbar/SearchCard/Datepicker/Datepicker.jsx:28
    • 您将其设置为状态,而不是在道具中设置它,伙计。您只能从父组件获取道具。
    • 那你能告诉我如何正确地做吗?我的意思是我真的有点迷失了,我需要通过,所以我可以使用选择的日期进入预订流程的下一阶段
    • 我试过类似`this.state = { value: "{this.props.value}" };`
    猜你喜欢
    • 1970-01-01
    • 2011-11-05
    • 2021-12-08
    • 2013-03-08
    • 2016-12-05
    • 1970-01-01
    • 2010-09-07
    • 2020-04-24
    • 1970-01-01
    相关资源
    最近更新 更多