如何在不使用 Redux 的情况下在 React 中将变量值从子项发送到父项

我有一个 Blog 组件,里面有一个 Search 组件。我需要访问searchResults我的博客组件中的变量。如何将它从搜索组件传递到博客组件?


这是父级(博客组件):


import React, { useState, useEffect } from 'react';

import axios from 'axios';

import Pagination from "react-pagination-js";

import Spinner from '../Spinner/Spinner';

import { Link } from 'react-router-dom';

import Footer from '../Footer/Footer.jsx';

import CustomHeader from '../CustomHeader/CustomHeader.jsx';

import Search from '../Search/Search.jsx';




const Blog = () => {


  let title = 'Articles'


  let [posts, setPosts] = useState([]);

  let [isMounted] = useState(false)

  let [currentPage, setCurrentPage] = useState(1);

  let [loading, setLoading] = useState(false);

  let [isVisible] = useState(true);

  const [postsPerPage] = useState(5);

  const GET_POSTS_API = process.env.REACT_APP_GET_POSTS_API;




  useEffect(() => {

    const fetchPosts = async () => {

      isMounted = true;

      setLoading(true);

      if (isMounted) {

        let res = await axios.get(GET_POSTS_API);

        setPosts(res.data);

      }

      setLoading(false);

    };


    fetchPosts();

  }, []);


  isMounted = false

  // Get current posts

  const indexOfLastPost = currentPage * postsPerPage;

  const indexOfFirstPost = indexOfLastPost - postsPerPage;

  const currentPosts = posts.slice(indexOfFirstPost, indexOfLastPost);

  let totalPagesGenerated = posts.length / postsPerPage;

  let totalPagesGeneratedCeiled = Math.ceil(totalPagesGenerated);

  if (loading) {

    return <Spinner />

  }


  // Change page

  const paginate = (pageNumber) => {

    Math.ceil(totalPagesGenerated)

    if (pageNumber > 0 && pageNumber <= totalPagesGeneratedCeiled) {

      setCurrentPage(pageNumber);

    }

  }

慕斯709654
浏览 110回答 3
3回答

回首忆惘然

我更喜欢两种将变量传递给子组件的方法。它们在不同的情况下都有用方法一:使用属性 => Props如果您的组件树嵌套不深,则此方法很有用。例如,您希望将变量从父项传递给子项。一个嵌套的组件如下const ParentComponent = () => {&nbsp;&nbsp; &nbsp; &nbsp;const [variable, setVariable] = useState(0);&nbsp; &nbsp; &nbsp;return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<ChildComponent variable={variable} setVariable={setVariable} /> //nested within ParentComponent, first level&nbsp; &nbsp; &nbsp; )}const ChildComponent = (props) => {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; return(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div>prop value is {props.variable}</div> //variable attribute available through component props&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button onClick={props.setVariable(prevValue => prevValue+1}>add +1</button> //set value in parent through callBack method&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </>&nbsp; &nbsp; &nbsp; &nbsp;)}如果你有一个高度嵌套的组件层次结构,事情就会变得有点混乱。比方说, ChildComponent 返回另一个组件,并且您希望variable将 传递给该组件,但是 ChildComponent 不需要该变量,您最终会遇到这种情况const ParentComponent = () => {&nbsp;&nbsp; &nbsp; &nbsp;const [variable, setVariable] = useState(false);&nbsp; &nbsp; &nbsp;return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<ChildComponent someProp={variable}/> //nested within ParentComponent, first level&nbsp; &nbsp; &nbsp; )}const ChildComponent = (props) => {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; return(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <AnotherCustomComponent someProp={props.someProps}/> //someProp attribute available through component props&nbsp; &nbsp; &nbsp; &nbsp;)}const AnotherCustomComponent = (props) => {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; return(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div>prop value is {props.someProp}</div> //someProp attribute available through component props&nbsp; &nbsp; &nbsp; &nbsp;)}即使 ChildComponent 不需要该道具,它也需要通过道具将其推送到其子组件。这被称为“螺旋桨钻井”。这是一个简单的示例,但对于更复杂的系统,它可能会变得非常混乱。为此,我们使用...方法二:Context API CodeSandbox上下文 API 提供了一种向子组件提供状态的巧妙方法,而不会以道具钻井情况结束。它需要一个Provideris setup,它将它的值提供给它的任何Consumers'. Any component that is a child of the Provider 可以使用上下文。首先创建一段上下文。CustomContext.jsimport React from 'react';const CustomContext = React.createContext();export function useCustomContext() {&nbsp; return React.useContext(CustomContext);}export default CustomContext;接下来是实现提供者,并给它一个值。我们可以使用之前的 ParentComponent 并添加 Context providerimport CustomContext from './CustomContext'const ParentComponent = () => {&nbsp; const [variable, setVariable] = useState(false);&nbsp; const providerState = {&nbsp; &nbsp; variable,&nbsp; &nbsp; setVariable&nbsp; }&nbsp; return (&nbsp; &nbsp; <CustomContext.Provider value={providerState} >&nbsp; &nbsp; &nbsp; <ChildComponent />&nbsp; &nbsp; </CustomContext.Provider>&nbsp; )}现在任何嵌套在 <CustomContext.Provider></CustomContext.Provider> 中的组件都可以访问传递到Provider我们嵌套的子组件看起来像这样const ChildComponent = (props) => {&nbsp; return(&nbsp; &nbsp; &nbsp; <AnotherCustomComponent/> //Notice we arent passing the prop here anymore&nbsp; &nbsp;)}const AnotherCustomComponent = (props) => {&nbsp; const {variable, setVariable} = useCustomContext(); //This will get the value of the "value" prop we gave to the provider at the parent level&nbsp; return(&nbsp; &nbsp; &nbsp; <div>prop value is {variable}</div> //variable pulled from Context&nbsp; &nbsp;)}如果 ParentComponent 被使用两次,则 ParentComponent 的每个实例都将有自己的“CustomContext”可供其子组件使用。const App() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ParentComponent/>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ParentComponent/>&nbsp; &nbsp; &nbsp; &nbsp; </>&nbsp; &nbsp;&nbsp;}

幕布斯7119047

您可以使用回调函数来执行此操作。您基本上将一个函数传递给您的子组件,您的子组件将触发该函数,而父组件将具有该值。这是一个应该如何实现的简单示例:家长:const Parent = () => {&nbsp; const onSearchResult = searchResults => {&nbsp; &nbsp; console.log(searchResults)&nbsp;}&nbsp; return (&nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; I am the parent component&nbsp; &nbsp; &nbsp; <Child onSearchResult={onSearchResult} />&nbsp; &nbsp; </>&nbsp; )}孩子:const Child = onSearchResult => {&nbsp; const calculateResults = e => {&nbsp; &nbsp; const results = doSomeStuff(e)&nbsp; &nbsp; onSearchResult(results)&nbsp; }&nbsp; return (&nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; I am the child component&nbsp; &nbsp; &nbsp; I have a component that will return some value&nbsp; &nbsp; &nbsp; <input onKeyPress={e => calculateResults(e)}&nbsp; &nbsp; </>&nbsp; )}

不负相思意

子组件应该从父组件那里获取一个回调属性。有点像按钮的工作方式:<Button&nbsp;onClick={this.onButtonClick}你想要的是做<SearchComponent&nbsp;onSearchResults={this.onResults}然后,在搜索组件中,您可以调用this.props.onSearchResults(searchResults);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript