【问题标题】:How to render a component B only after selecting a radio button in component A in react js?仅在 react js 中选择组件 A 中的单选按钮后,如何渲染组件 B?
【发布时间】:2020-01-16 01:43:07
【问题描述】:

我是 React 新手。我有三个组件 A、B 和 C。我只需要在选择 A 中列出的单选按钮后渲染 C。我没有找到方法。有人可以建议最好的方法吗?

【问题讨论】:

  • 您能告诉我们自己尝试解决这个问题吗?

标签: reactjs conditional-statements rendering


【解决方案1】:

这个想法基本上是 A 和 C 都“更高”的东西应该存储一个变量来判断 C 是否可见,然后将它传递给 C。更高的东西可能是它们的父状态或 mobx 存储,或设置在挂钩上的变量... A 和 C 都可以访问的任何内容,当其值更改时会触发 C 中的重新渲染。

在过去,我们会这样做:

class ParentComponent extends React {
    state = { showC: false }
    toggleShowC = () => this.setState({ showC: !this.state.showC })
    render () {
        <>
            <A toggleShowC={this.toggleShowC} />
            <B />
            <C showC={this.state.showC} />
        </>
    }
}

const C = props => (
    props.showC
        ? <The goodies go here />
        : null
)

这不是一个非常复杂的例子。我鼓励您尝试使用react hooks 重新创建类似的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-30
    • 2020-05-21
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    相关资源
    最近更新 更多