Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

reactjs - Appending JSX Block Rather Than Repeating Block Based on Condition

In my React app I have a function that returns one block of JSX or another based on a condition. This works as expected. The thing is, the only difference between the two blocks is that in the second case an icon is included, to allow for clearing the search text, since text now exists. When there is no text the icon is not included (hence the other condition).

While this is working, I'm wondering, since the only difference between the two blocks of code is the inclusion of the icon, if there is a way I can just append it somehow, rather than repeating the block of code, as I am doing now?

This is the function:

  renderIDFilter = () => {
    if (this.props.filters.id) {
      return (
        <SearchBox
          label="ID:"
          defaultValue={this.props.filters.id}
          onChange={this._onFilterById}
          styles={{ iconContainer: { display: "none" }, root: { maxWidth: 300 } }}
          borderless
          underlined
          iconProps={{ 
            style: { pointerEvents: 'auto', cursor: 'pointer' },
            iconName: 'clear', onClick: () => { 
              this.clearFilter('ID');
            }
          }}
      />
      )
    } else {
      return (
        <SearchBox
          label="ID:"
          defaultValue={this.props.filters.id}
          onChange={this._onFilterById}
          styles={{ iconContainer: { display: "none" }, root: { maxWidth: 300 } }}
          borderless
          underlined
      />
      )
    }
  }
question from:https://stackoverflow.com/questions/65848267/appending-jsx-block-rather-than-repeating-block-based-on-condition

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try something like this:

renderIDFilter = () => {
      return (
        <SearchBox
          label="ID:"
          defaultValue={this.props.filters.id}
          onChange={this._onFilterById}
          styles={{ iconContainer: { display: "none" }, root: { maxWidth: 300 } }}
          borderless
          underlined
          iconProps={this.props.filters.id?{ 
            style: { pointerEvents: 'auto', cursor: 'pointer' },
            iconName: 'clear', onClick: () => { 
              this.clearFilter('ID');
            }
          }:null or undefined or {}}
      />
      )
    }
  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...