【问题标题】:Struggling with this.props in nested components在嵌套组件中使用 this.props
【发布时间】:2019-11-07 20:25:04
【问题描述】:

抱歉,如果这是一个基本问题,但我是 react/gatsby 新手,我正在努力寻找问题的答案,因为我不确定确切的术语。

我目前正在使用原子设计原则构建一个网站。我想在站点周围使用按钮/表单等原子组件时更新它们的副本 - 但是我正在努力使用我知道的方法传递数据。


代码设置

Atom/Button 组件文本是这样编码的
<button>{this.props.copy}</button>

英雄横幅等布局组件 使用
<section>This is a hero banner <button copy="copy goes here" /></section>

将按钮导入布局中

页面组件我想在各个页面中使用布局/英雄组件,我已经导入了布局组件并覆盖了布局组件中已经定义的按钮文本,但是使用
@987654323 @
显然行不通


有没有办法将一个组件拉入另一个组件,例如<hero <button copy="new copy"/> /> 并覆盖该道具。或者在可以嵌套的原子组件中定义道具的更好方法。所以结构看起来是这样的(第三级组件总是在布局中,很少自己拉到页面中。)

第 1 页
第 2 页
├── 布局(英雄)
├──────── 原子(按钮)
├──────── 原子(输入)
└──────── 原子(选择)

任何帮助将不胜感激。

【问题讨论】:

  • 您是否尝试将组件分配给变量?并将 var 作为 prop 传递?

标签: reactjs jsx gatsby


【解决方案1】:

你有几个选择:

  1. Prop Drilling
  2. Render Props (React docs)。

我要说的是尽可能避免 Prop Drilling。它在大型组件层次结构上变得很麻烦。尝试使用 render props 更动态的方法,让您在不引起问题的情况下更换实现。

道具钻孔:

这将涉及向下传递组件层次结构的道具。对于您的用例,它看起来像这样

class Layout extends Component {
    render() {
        return (
            <section>
                This is a hero banner <AtomButton copy={this.props.copy} /> 
            </section>
        )
    }
}

class AtomButton extends Component {
    render() {
        return (
            <button>this.props.copy</button>
        )
    }
}

渲染道具:

我在这里展示的实际上并不是一个渲染道具。这只是将一个组件作为 prop 向下传递,然后对组件进行 rednering。在我链接的 React 文档中定义了真正的渲染道具。

class Layout extends Component {
    render() {
        return (
            <section> This is a hero banner {this.props.button} /><section>
        )
    }
}

//Wherever your are loading your Layout Component
class Page extends Component {
    render() {
        return (
            <Layout buttonRender={<AtomButton copy="overwrite copy" />} />              
        )
    }
}

【讨论】:

    猜你喜欢
    • 2017-12-31
    • 2018-09-11
    • 2017-02-14
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    • 2021-11-24
    相关资源
    最近更新 更多