简体   繁体   English

使用道具和状态将选择框的值传递给子组件 React.JS

[英]Using Props And State To Pass Value Of Select Box To Child Component React.JS

Background背景

I am going to be filtering a table based on the values in a selection box.我将根据选择框中的值过滤表格。 I am having trouble understanding state and props within react.js .我无法理解react.js stateprops Once I pass the value in I can easily do the filtering but I am trying to do this the "react" way.一旦我传递了值,我就可以轻松地进行过滤,但我正在尝试以“反应”的方式来做到这一点。

Question

How do I pass the value of SelectionBox when it is selected or changed to TableDisplay when the user selects one of the options?当用户选择其中一个选项时, TableDisplay在选择或更改为TableDisplay时传递SelectionBox的值?

Example例子

class SelectionBox extends React.Component {
                render() {
                return <div className="filter">
              <label for="business">Filter by Status
                                <select id="business" name="business">
                                    <option value="all">All Requests</option>
                                    <option value="approved">Approved</option>
                                    <option value="pending">Pending</option>
                                    <option value="denied">Denied</option>
                                </select>
                </label>
            </div>;
        }
}

class TableDisplay extends React.Component {
        render() {
            return <div className="wrapper">
            <h1>Requests</h1>
            <SelectionBox /> 
            <div><table className="table">
                    <tr className="seperate"><td>Title</td><td>Status</td><td>Created</td><td>Updated</td><td>Delete</td></tr>
                  {Object.keys(requests).map(function(key) {  
    let styling = "bg-plain";

    if (requests[key].status == "Approved") {
        styling = "bg-success";
    } else if (requests[key].status == "Denied") {
        styling = "bg-danger";
    }

    return <tr className={styling}>
        <td>{requests[key].title}</td>
        <td>{requests[key].status}</td>
        <td>{requests[key].created_at.slice(0, 10)}</td>
        <td>{requests[key].updated_at.slice(0, 10)}</td>
        <td><a href="">Delete</a></td>
    </tr>;

    })}
                    </table>
          </div></div>;
      }
}

Research研究

From reading I think what I need to implement here is, Inside SelectionBox从阅读中我认为我需要在这里实现的是,Inside SelectionBox

 constructor(props) {
    super(props);

    this.state = {
// Something referring to the state of the select box here
    };
  };

Then access props from within TableDisplay ?然后从TableDisplay访问props

First, to clear up your understanding of state vs props you should reference this answer: What is the difference between state and props in React?首先,为了澄清你对stateprops理解,你应该参考这个答案: React 中 state 和 props 之间有什么区别?

Second, to pass the value of the SelectionBox to the TableDisplay you need to create some kind of parent TableDisplayContainer component that contains both components.其次,要将SelectionBox的值传递给TableDisplay您需要创建某种包含这两个组件的父TableDisplayContainer组件。 The TableDisplayContainer will store the value of the select dropdown in its state. TableDisplayContainer将在其状态中存储select下拉列表的值。 To do this, you need to pass a function as a prop to the SelectionBox that will handle the onChange event of the select dropdown (you can call it handleOnChange for example).为此,您需要将一个函数作为道具传递给将处理select下拉列表的onChange事件的SelectionBox (例如,您可以将其handleOnChange )。 The handleOnChange method will set the value to the state of the TableDisplayContainer . handleOnChange方法会将值设置为TableDisplayContainer的状态。 Once it's set in state, you can pass the value to the TableDisplay component as a prop.一旦它设置为状态,您就可以将该值作为道具传递给TableDisplay组件。

Here's a quick example of what you can do:以下是您可以执行的操作的快速示例:

class SelectionBox extends React.Component {
  render() {
    return (
      <div className="filter">
        <label for="business">Filter by Status
          <select
            id="business"
            name="business"
            onChange={this.props.handleOnChange}
          >
              <option value="all">All Requests</option>
              <option value="approved">Approved</option>
              <option value="pending">Pending</option>
              <option value="denied">Denied</option>
          </select>
        </label>
      </div>
    );
  }
}

class TableDisplay extends React.Component {
  render() {
    // Do your filtering with this value
    const {selectValue} = this.props;

    return (
      <div className="wrapper">
        <h1>Requests</h1>
        <SelectionBox /> 
        <div><table className="table">
              <tr className="seperate"><td>Title</td><td>Status</td><td>Created</td><td>Updated</td><td>Delete</td></tr>
            {Object.keys(requests).map(function(key) {  
        let styling = "bg-plain";

        if (requests[key].status == "Approved") {
        styling = "bg-success";
        } else if (requests[key].status == "Denied") {
        styling = "bg-danger";
        }

        return <tr className={styling}>
        <td>{requests[key].title}</td>
        <td>{requests[key].status}</td>
        <td>{requests[key].created_at.slice(0, 10)}</td>
        <td>{requests[key].updated_at.slice(0, 10)}</td>
        <td><a href="">Delete</a></td>
        </tr>;

        })}
              </table>
        </div>
      </div>
    );
  }
}
class TableDisplayContainer extends React.Component {
  constructor() {
    super();
    this.state = {
      selectValue: 'all' // use this as default
    }
  }

  handleOnChange(e) {
    this.setState({
      selectValue: e.target.value
    });
  }

  render() {
    const {selectValue} = this.state;

    return (
      <div>
        <SelectionBox
          handleOnChange={this.handleOnChange.bind(this)}
        />
        <TableDisplay
          selectValue={selectValue}
        />
      </div>
    )
  }
}

On React state is something that is relevant to the component itself, and props are passed down to it (or have a default value in case of omission). React 状态是与组件本身相关的东西,并且道具被传递给它(或者在遗漏的情况下具有默认值)。 The handle events guide explains my solution below: 处理事件指南在下面解释了我的解决方案:

You can pass a onChange handler to selectionBox and use it on your TableDisplay component您可以将 onChange 处理程序传递给 selectionBox 并在您的 TableDisplay 组件上使用它

  class SelectionBox extends React.Component {
    render () {
      //...
        <select onChange={this.props.onChange}>
          //...
        </select>
      //...
    }
  }
  SelectionBox.propTypes = {
    onChange: PropTypes.func.isRequired
  }
  class TableDisplay extends React.Component {
    constructor(props) {
      super(props)
      this.onSelection = this._onSelection.bind(this)
      this.state = {
        selectValue: null
      }
    }
    _onSelection (ev) {
      this.setState({selectValue:ev.target.value})
    }
    render () {
      //...
      <SelectionBox onChange={this.props.onSelection} />
      //...
      <h1>{'The select value is '+ this.state.selectValue}</h1>
    }
}

Notice that I used propTypes just to make sure that I don't forget.请注意,我使用propTypes只是为了确保我不会忘记。

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

相关问题 将更新的父状态传递给子道具 React.js - Pass updated parent state to child props React.js 如何将对象作为道具传递给 React.js 中的子功能组件? - How to pass an object as props to a child Functional Component in React.js? 如何使用 react.js 中的编程路由将道具从子组件(addform)传递到主应用程序组件 - How to pass props from child component (addform) to main app component using programmatic routing in react.js 如何在 React.js 中将 state 作为道具从父母传递给孩子,然后从该孩子传递给它的孩子 - How to pass state from parent to child as props then from that child to it s child as props in React.js 如何在React.JS中将状态从子组件传递给父组件? - How to pass state from child component to parent in React.JS? 如何使用React.js将状态属性传递给构造函数中的子组件? - How to pass state property to child component in constructor with React.js? React.js - 子组件道具未定义 - React.js - child component props undefined 在 React.js 中将 props 传递给父组件 - Pass props to parent component in React.js 如何通过道具[REACT.JS]将图片网址从父组件传递到子组件 - How can I pass image url from parent component to child component via props [REACT.JS] 如何在 React.js 功能组件中将子组件 state 传递给父组件 state? - How to pass child component state to parent component state in React.js functional components?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM