亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在不使用 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 不需要該道具,它也需要通過道具將其推送到其子組件。這被稱為“螺旋槳鉆井”。這是一個簡單的示例,但對于更復雜的系統,它可能會變得非?;靵y。為此,我們使用...


方法二: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 關注
  • 156 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號