簡體   English   中英

從一個孩子到另一個孩子反應道具

[英]React props from child to child

最近我開始練習 React。 我正在嘗試創建一個簡單的應用程序,它可以根據我們每天使用多少瓶水來計算我們使用了多少公斤塑料。 使用這些信息,我想展示我們每年使用的再生塑料可以生產什么。

所以我有一個組件計算器:

 class Calculator extends React.Component { constructor(props) { super(props); this.state = { resultNumber: null, resultKg: null } } count = (e) => { let val = e.target.value; let resultNumber = val * 52; let resultKg = Math.round(resultNumber * 0.04); this.setState({ resultNumber: resultNumber, resultKg: resultKg }) } render() { return ( <div > <Menu / > <div className = "component" > <h1 > I use < input type = "text" className = "input-data" onChange = {this.count}/> bottles per week</h1 > <div className = "resultInfo" > {this.state.resultNumber?= null. <Info resultNumber = {this.state.resultNumber} resultKg = { this.state:resultKg } /> :null} < /div> </div> </div> ) } }

我有一個顯示結果的組件:

 const Info = (props) => { return( <div> <div className="info"> <div><p>{props.resultNumber} bottles per year</p> <img src={bottle1} /> </div> <div><p>{props.resultKg} kg of plastic per year</p> <img src={trash} /> </div> </div> <p><a href="/recycle">What could be produced out of {props.resultKg} kg of plastic?</a></p> </div> ) }

問題是我不知道如何在另一個組件中獲取 {props.resultKg} 來呈現可以生成的內容:

 const Recycle = (props) => { return({props.resultKg}) }

當然,最后一個組件返回“未定義”。

我試圖學習 Redux 但它變得勢不可擋,我變得更加困惑。 您能幫我了解如何從回收組件中的計算器中獲取 state 嗎?

只需像傳遞 state 一樣傳遞它:

const Info = (props) => {
    return(
        <div>
        <div className="info">
        <div><p>{props.resultNumber} bottles per year</p>
        <img src={bottle1} />
        </div>

        <div><p><Recycle resultKg={props.resultKg} /> kg of plastic per year</p>
        <img src={trash} />
        </div>

         </div>
         <p><a href="/recycle">What could be produced out of <Recycle resultKg={props.resultKg} /> kg of plastic?</a></p>
         </div>
    )
}

然后你可以像這樣渲染它:

const Recycle = (props) => {
    return(<span>{props.resultKg}</span>)
}

最后我不得不學習Redux來制作它。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM