【问题标题】:Access children properties (state?) from parent从父级访问子级属性(状态?)
【发布时间】:2021-11-05 17:44:27
【问题描述】:

我正在构建我的第一个 React 应用程序,我对如何在组件之间进行通信有点困惑。

应用程序计算某个游戏的玩家的分数。为此,我创建了一个组件数组,然后我需要对父组件中每个组件的分数求和。

各个组件的代码如下:

家长:

const RouteScore = () => {
    const routes = [
        { length: 1, score: 1 },
        { length: 2, score: 2 },
        { length: 3, score: 4 },
        { length: 4, score: 7 },
        { length: 6, score: 15 },
        { length: 8, score: 21 },
    ]

    const buttons = routes.map((route) => <RouteScoreButton length={route.length} score={route.score} key={route.length} />)

    return (
        <div className="position-absolute top-50 start-50 translate-middle">
            <div className="bg-light border border-primary rounded-3 px-4 py-4 opacity-75 text-center">
                <table className="table">
                    <thead>
                        <tr className="text-center">
                            <th scope="col">Route length</th>
                            <th scope="col">Total routes</th>
                            <th scope="col">Total score</th>
                        </tr>
                    </thead>
                    <tbody className="text-center align-middle">
                        {buttons}
                    </tbody>
                </table>
                <h3>Total score:</h3>
            </div>
        </div>
    )
}

儿童:

const RouteScoreButton = (props) => {
    const [numberRoutes, setNumberRoutes] = useState(0)
    const score = useMemo(() => props.score * numberRoutes, [numberRoutes])

    const increaseRoute = () => {
        setNumberRoutes(numberRoutes + 1)
    }
    const decreaseRoute = () => {
        numberRoutes > 0 && setNumberRoutes(numberRoutes - 1)
    }

    const handleChange = (e) => {
        let newValue = parseInt(e.target.value)
        if (isNaN(newValue)) {
            setNumberRoutes(0)
        } else {
            setNumberRoutes(parseInt(e.target.value))
        }
    }

    return (
        <tr>
            <th>
                <h3>{props.length}</h3>
            </th>
            <th>
                <div className="input-group" role="group" aria-label="Basic example">
                    <button type="button" className="btn btn-primary" onClick={increaseRoute}>+</button>
                    <input type="text" className="form-control text-center" style={{ width: '50px' }} value={numberRoutes} onChange={handleChange} />
                    <button type="button" className="btn btn-primary" onClick={decreaseRoute}>-</button>
                </div>
            </th>
            <th>
                <h3>{score}</h3>
            </th>
        </tr>
    )
}

如何计算每个子组件的分数总和?

【问题讨论】:

    标签: reactjs react-functional-component


    【解决方案1】:

    在这种情况下,最好将状态上移一级,所以在父级中会是

    const RouteScore = () => {
        const [routes, setRoutes] = useState([
            { length: 1, score: 1, numberRoutes: 0 },
            { length: 2, score: 2, numberRoutes: 0 },
            { length: 3, score: 4, numberRoutes: 0 },
            { length: 4, score: 7, numberRoutes: 0 },
            { length: 6, score: 15, numberRoutes: 0 },
            { length: 8, score: 21, numberRoutes: 0 },
        ]);
    
        const handleRouteChange = (length, numberRoutes) => {
           const newRoutes = routes.map(elem => 
                if (elem.length === length){
                    return {...elem, score: numberRoutes*length, numberRoutes}
                }
                return elem;
           )
           setRoutes(newRoutes);
        }
    
        const buttons = routes.map((route) => 
           <RouteScoreButton length={route.length} score={route.score} key={route.length} handleRouteChange={handleRouteChange}/>)
    
        return (
            <div className="position-absolute top-50 start-50 translate-middle">
                <div className="bg-light border border-primary rounded-3 px-4 py-4 opacity-75 text-center">
                    <table className="table">
                        <thead>
                            <tr className="text-center">
                                <th scope="col">Route length</th>
                                <th scope="col">Total routes</th>
                                <th scope="col">Total score</th>
                            </tr>
                        </thead>
                        <tbody className="text-center align-middle">
                            {buttons}
                        </tbody>
                    </table>
                    <h3>Total score:</h3>
                </div>
            </div>
        )
    }
    

    在孩子中

    const RouteScoreButton = (props) => {
      
        const increaseRoute = () => {
            props.handleRouteChange(props.length, props.numberRoutes + 1)
        }
        const decreaseRoute = () => {
            props.numberRoutes > 0 && props.handleRouteChange(props.length, props.numberRoutes - 1)
        }
    
        const handleChange = (e) => {
            let newValue = parseInt(e.target.value)
            if (isNaN(newValue)) {
                props.handleRouteChange(props.length, 0)
            } else {
                props.handleRouteChange(props.length, parseInt(e.target.value))
            }
        }
    
        return (
            <tr>
                <th>
                    <h3>{props.length}</h3>
                </th>
                <th>
                    <div className="input-group" role="group" aria-label="Basic example">
                        <button type="button" className="btn btn-primary" onClick={increaseRoute}>+</button>
                        <input type="text" className="form-control text-center" style={{ width: '50px' }} value={numberRoutes} onChange={handleChange} />
                        <button type="button" className="btn btn-primary" onClick={decreaseRoute}>-</button>
                    </div>
                </th>
                <th>
                    <h3>{score}</h3>
                </th>
            </tr>
        )
    }
    

    这将是一个更好的方法。

    出于某种原因,如果您仍希望父级访问子级状态。你可以查看useImperativeHandle钩子。

    【讨论】:

    • 谢谢!,成功了。 (我认为我的变量命名让你感到困惑,但我让它起作用了)
    • 太棒了。你能接受答案吗?所以它会帮助别人。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 2020-10-05
    相关资源
    最近更新 更多