如何将值从一个组件传递到另一组件?

时间:2020-09-12 17:38:31

标签: javascript reactjs components react-props

我有SearchBox.js组件,该组件设置两个值onChange我想将选择值和输入值onClick onSumbit传递给Movie.js组件,我只能传递一个值,但不能传递第二个值(yearValue),是否存在将两个值传递给Movie.js组件的方法。

function SearchBox(props) {
  const [searchValue, setSearchValue] = useState("");
  const [yearValue, setYearValue] = useState("");
  const getDropList = () => {
    const year = new Date().getFullYear();
    return Array.from(new Array(121), (v, i) => (
      <option key={i} value={year - i}>
        {year - i}
      </option>
    ));
  };
  return (
    <div>
      <Container>
        <Row>
          <Col>
            <InputGroup className="mb-3">
              <select value={yearValue} onChange={e => setYearValue(e.target.value)}>
                {getDropList()}
              </select>
              <FormControl
                value={searchValue}
                type="text"
                name="searchValue"
                onChange={e => setSearchValue(e.target.value)}
                placeholder="Search by title"
                aria-describedby="basic-addon2"
              />
              <InputGroup.Append>
                <Button
                  onClick={() => props.onSubmit(searchValue)}
                  variant="dark"
                >
                  Search
                </Button>
              </InputGroup.Append>
            </InputGroup>
          </Col>
        </Row>
      </Container>
    </div>
  );
}
export default SearchBox;


function Movie() {
const [data, setData] = useState(null);
 const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
 const [q, setQuery] = useState("");
const [activateModal, setActivateModal] = useState(false);
 const [detail, setShowDetail] = useState(false);
const [detailRequest, setDetailRequest] = useState(false);
 const [year,setYear] = useState("")

 return (
   <div>
      <Row>
        <Col>
          <SearchBox onSubmit={setQuery} />
        </Col>  
      </Row>

2 个答案:

答案 0 :(得分:0)

您可以像这样传递两个值:

<Button
                  onClick={() => props.onSubmit(searchValue,yearValue)}
                  variant="dark"
                >
                  Search
                </Button>

内部Movie组件。捕获这些值:

function Movie() {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);
  const [q, setQuery] = useState("");
  const [activateModal, setActivateModal] = useState(false);
  const [detail, setShowDetail] = useState(false);
  const [detailRequest, setDetailRequest] = useState(false);
  const [year, setYear] = useState("");

  const handleSubmit = (selectValue,yearValue) => {
    //do whatever you want to do
  }
  return (
    <div>
      <Row>
        <Col>
          <SearchBox onSubmit={handleSubmit} />
        </Col>
      </Row>
    </div>
  );
}


答案 1 :(得分:0)

您可能想看一下React Docs,以了解Render Props技术。

术语“渲染道具”是指一种用于在 使用价值为函数的道具来反应组件。 了解更多信息here