学习者问题:如何有条件地为此特定代码设置包装器。反应/ SPFX

时间:2019-12-16 15:38:28

标签: javascript reactjs jsx spfx

我试图将<Fade />应用于渲染器中的代码块,但前提是this.state.ContextNewJobFade为false。

我已经完全阅读了How do I conditionally wrap a React component?,但仍然不知道如何使用我的代码来实现它。编辑后的解决方案:我相信这个问题与上面的问题非常相似,但是它使用了Fade包装而不是href链接。

这是渲染的方块:

<div>
{this.state.ContextNewJobFade === false ?
  <Fade>
    <Label className={styles.questionTitle1}>Text:</Label>
    <br />

    <div className={styles.questionDescription}>
      Text
      <br />
    </div>
    <br />
    <TextField
      name="txtContextNewJobCode"
      multiline
      resizable={false}
      value={this.state.ContNewJobCode}
      onChange={this._onContNewJobCodeChng}
    />
  </Fade>
) : (
  <div>
    <Label className={styles.questionTitle1}>Some Text</Label>
    <br />

    <div className={styles.questionDescription}>
      Text
      <br />
    </div>
    <br />
    <TextField
      name="txtContextNewJobCode"
      multiline
      resizable={false}
      value={this.state.ContNewJobCode}
      onChange={this._onContNewJobCodeChng}
    />
  </div>
);

如您所见,我正在此处复制代码,需要更好的解决方案。

1 个答案:

答案 0 :(得分:3)

这就是我重构您的组件的方式,希望对您有所帮助!

const FadeComponent = ({ fade, children }) =>
  fade ? <Fade>{children}</Fade> : children;

const MyComponent = () => {
  return (
    <FadeComponent fade={this.state.ContextNewJobFade}>
      <Label className={styles.questionTitle1}>Text:</Label>
      <br />

      <div className={styles.questionDescription}>
        Text
        <br />
      </div>
      <br />
      <TextField
        name='txtContextNewJobCode'
        multiline
        resizable={false}
        value={this.state.ContNewJobCode}
        onChange={this._onContNewJobCodeChng}
      />
    </FadeComponent>
  );
};