简体   繁体   English

React:编写一个函数作为道具传递

[英]React: Writing a function to pass as a prop

Basically, I've been tasked with editing a UI as a mini challenge to help get me into programming.基本上,我的任务是编辑 UI 作为帮助我进入编程的小挑战。

I want to add a date picker to my search bar in order to narrow down the search to between two dates.我想在我的搜索栏中添加一个日期选择器,以便将搜索范围缩小到两个日期之间。 I have the UI working, although when the user selects a date using the picker, the date on the picker doesn't update.我有 UI 工作,虽然当用户使用选择器选择日期时,选择器上的日期不会更新。 Nothing happens, and I'm not sure why.什么也没发生,我不知道为什么。

Here is my code:这是我的代码:

Search box:搜索框:

import React from "react";

import { TextField, Button, Typography } from "@material-ui/core";

import "./SearchBox.css"
import DatePickerWidget from "./DatePickerWidget"

class SearchBox extends React.Component {
  constructor(props) {
    super(props);
    this.state = { searchTerm: "", results: "" };

    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.validateSearch = this.validateSearch.bind(this);
    this.clear = this.clear.bind(this);



  
  }

  componentDidMount() {
    this.setState({ searchTerm: this.props.searchTerm });
  }
  componentDidUpdate(prevProps) {
    if (prevProps.searchTerm !== this.props.searchTerm)
      this.setState({ searchTerm: this.props.searchTerm });
  }

  handleChange(event) {
    this.setState({ [event.target.name]: event.target.value });
  }

  handleSubmit(event) {
    event.preventDefault();
    this.props.update({ searchTerm: this.state.searchTerm });
    this.setState({ results: this.state.searchTerm });
  }

  validateSearch() {
    return this.state.searchTerm !== "";
  }

  clear() {
    this.setState({ searchTerm: "", results: "" });
    this.props.update({ searchTerm: "" });
  }

  render() {
    return (
      <React.Fragment>
        <form id="search-form" onSubmit={this.handleSubmit}>
          <Button
            style={{ width: "40%" }}
            variant="outlined"
            color="primary"
            onClick={this.clear}
            disabled={this.state.results === ""}
          >
            Clear
          </Button>
          <TextField
            style={{ flexBasis: "100%" }}
            variant="outlined"
            label="Search Term"
            type="search"
            name="searchTerm"
            value={this.state.searchTerm}
            onChange={this.handleChange}
          />
          <Button
            style={{ width: "40%" }}
            variant="contained"
            color="primary"
            disabled={!this.validateSearch()}
            type="submit"
          >
            Search
          </Button>

          <DatePickerWidget update={this.props.update}/>

        </form>
        {this.state.results && (
          <Typography align="center" variant="body1">
            Displaying results for: {this.state.results}
          </Typography>
        )}
      </React.Fragment>
    );
  }
}


export default SearchBox;

Date picker widget:日期选择器小部件:

import React from "react";
import "date-fns";

import { Paper } from "@material-ui/core";

import DateFnsUtils from "@date-io/date-fns";
import {
  MuiPickersUtilsProvider,
  KeyboardDatePicker,
} from "@material-ui/pickers";

class DatePickerWidget extends React.Component {
  render() {
    return (
      <Paper id="date-picker-widget" elevation={8}>
        <Paper id="date-filters" elevation={8}>
          <MuiPickersUtilsProvider utils={DateFnsUtils}>
            <KeyboardDatePicker
              margin="normal"
              id="date-picker-dialog"
              label="Start Date"
              format="yyyy/MM/dd"
              value={this.props.startDate}
              maxDate={this.props.endDate}
              onChange={(date) => this.props.update({ startDate: date })}
              KeyboardButtonProps={{
                "aria-label": "change start date",
              }}
            />
            <KeyboardDatePicker
              margin="normal"
              id="date-picker-dialog"
              label="End Date"
              format="yyyy/MM/dd"
              value={this.props.endDate}
              minDate={this.props.startDate}
              onChange={(date) => this.props.update({ endDate: date })}
              KeyboardButtonProps={{
                "aria-label": "change end date",
              }}
            />
          </MuiPickersUtilsProvider>
        </Paper>
      </Paper>
    );
  }
}

export default DatePickerWidget;

I know that I need to write a function called update and pass it to the date picker as a prop... i just don't actually know how to do that or what it should look like.我知道我需要编写一个名为 update 的函数并将它作为道具传递给日期选择器......我只是不知道如何做到这一点或它应该是什么样子。

Any help is appreciated as I'm just starting to enter this complicated programming world.感谢任何帮助,因为我刚刚开始进入这个复杂的编程世界。

Here is a codesandbox link for easier reference: https://codesandbox.io/s/bold-torvalds-phoxq这是一个代码和框链接,以便于参考: https ://codesandbox.io/s/bold-torvalds-phoxq

It looks like the problem is actually in your index.js file.看起来问题实际上出在您的index.js文件中。 You are importing DatePickerWidget instead of Searchbox .您正在导入DatePickerWidget而不是Searchbox Therefore, when you create your <App /> component you aren't passing an update function.因此,当您创建<App />组件时,您不会传递update函数。 I added an example where you are passing an update functionhere and it seems to work.我添加了一个例子,你在这里传递一个更新函数,它似乎工作。 I tried updating the code to use Searchbox instead, but there are other dependencies (CSS, etc.) that would need to be resolved.我尝试更新代码以改用Searchbox ,但还有其他依赖项(CSS 等)需要解决。 Let me know if that helps!如果这有帮助,请告诉我!

import React from "react";
import ReactDOM from "react-dom";

import App from "./DatePickerWidget";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <React.StrictMode>
    <App update={() => console.log("here")} />
  </React.StrictMode>,
  rootElement
);

Your DatePickerWidget isn't updating because it doesn't have a state , you should add a state in which upon the change to your dates is reflected.您的 DatePickerWidget 没有更新,因为它没有state ,您应该添加一个状态,在其中反映对您的日期的更改。

Ie DatePickerWidgetDatePickerWidget

You can add the update function and pass as below.您可以添加更新功能并通过如下方式。

const update = (value) => {
    console.log(value);
};
const rootElement = document.getElementById("root");
ReactDOM.render(
  <React.StrictMode>
     <App update={update} />
  </React.StrictMode>,
  rootElement
);

例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM