为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕斯709654 2023-01-06 11:12:33
我有一个 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);    }  }
查看完整描述

3 回答

?
回首忆惘然

TA贡献1847条经验 获得超11个赞

我更喜欢两种将变量传递给子组件的方法。它们在不同的情况下都有用


方法一:使用属性 => Props


如果您的组件树嵌套不深,则此方法很有用。例如,您希望将变量从父项传递给子项。


一个嵌套的组件如下


const ParentComponent = () => {

 

     const [variable, setVariable] = useState(0);


     return (

         <ChildComponent variable={variable} setVariable={setVariable} /> //nested within ParentComponent, first level

      )

}


const ChildComponent = (props) => {

    

      return(

          <>

              <div>prop value is {props.variable}</div> //variable attribute available through component props

              <button onClick={props.setVariable(prevValue => prevValue+1}>add +1</button> //set value in parent through callBack method

          </>

       )


}

如果你有一个高度嵌套的组件层次结构,事情就会变得有点混乱。比方说, ChildComponent 返回另一个组件,并且您希望variable将 传递给该组件,但是 ChildComponent 不需要该变量,您最终会遇到这种情况


const ParentComponent = () => {

 

     const [variable, setVariable] = useState(false);


     return (

         <ChildComponent someProp={variable}/> //nested within ParentComponent, first level

      )

}


const ChildComponent = (props) => {

    

      return(

          <AnotherCustomComponent someProp={props.someProps}/> //someProp attribute available through component props

       )


}



const AnotherCustomComponent = (props) => {

    

      return(

          <div>prop value is {props.someProp}</div> //someProp attribute available through component props

       )


}

即使 ChildComponent 不需要该道具,它也需要通过道具将其推送到其子组件。这被称为“螺旋桨钻井”。这是一个简单的示例,但对于更复杂的系统,它可能会变得非常混乱。为此,我们使用...


方法二:Context API CodeSandbox


上下文 API 提供了一种向子组件提供状态的巧妙方法,而不会以道具钻井情况结束。它需要一个Provideris setup,它将它的值提供给它的任何Consumers'. Any component that is a child of the Provider 可以使用上下文。


首先创建一段上下文。


CustomContext.js


import React from 'react';


const CustomContext = React.createContext();


export function useCustomContext() {

  return React.useContext(CustomContext);

}


export default CustomContext;

接下来是实现提供者,并给它一个值。我们可以使用之前的 ParentComponent 并添加 Context provider


import CustomContext from './CustomContext'


const ParentComponent = () => {


  const [variable, setVariable] = useState(false);


  const providerState = {

    variable,

    setVariable

  }


  return (

    <CustomContext.Provider value={providerState} >

      <ChildComponent />

    </CustomContext.Provider>

  )

}

现在任何嵌套在 <CustomContext.Provider></CustomContext.Provider> 中的组件都可以访问传递到Provider


我们嵌套的子组件看起来像这样


const ChildComponent = (props) => {


  return(

      <AnotherCustomComponent/> //Notice we arent passing the prop here anymore

   )


}



const AnotherCustomComponent = (props) => {


  const {variable, setVariable} = useCustomContext(); //This will get the value of the "value" prop we gave to the provider at the parent level


  return(

      <div>prop value is {variable}</div> //variable pulled from Context

   )


}

如果 ParentComponent 被使用两次,则 ParentComponent 的每个实例都将有自己的“CustomContext”可供其子组件使用。


const App() {


    return (

        <>

            <ParentComponent/> 

            <ParentComponent/>

        </>    


}


查看完整回答
反对 回复 2023-01-06
?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

您可以使用回调函数来执行此操作。


您基本上将一个函数传递给您的子组件,您的子组件将触发该函数,而父组件将具有该值。


这是一个应该如何实现的简单示例:


家长:


const Parent = () => {

  const onSearchResult = searchResults => {

    console.log(searchResults)

 }


  return (

    <>

      I am the parent component

      <Child onSearchResult={onSearchResult} />

    </>

  )

}

孩子:


const Child = onSearchResult => {

  const calculateResults = e => {

    const results = doSomeStuff(e)

    onSearchResult(results)

  }


  return (

    <>

      I am the child component

      I have a component that will return some value

      <input onKeyPress={e => calculateResults(e)}

    </>

  )

}


查看完整回答
反对 回复 2023-01-06
?
不负相思意

TA贡献1777条经验 获得超10个赞

子组件应该从父组件那里获取一个回调属性。有点像按钮的工作方式:

<Button onClick={this.onButtonClick}

你想要的是做

<SearchComponent onSearchResults={this.onResults}

然后,在搜索组件中,您可以调用this.props.onSearchResults(searchResults);


查看完整回答
反对 回复 2023-01-06
  • 3 回答
  • 0 关注
  • 108 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信