【问题标题】:Conditional rendering react to display components条件渲染对显示组件做出反应
【发布时间】:2020-03-15 03:11:59
【问题描述】:

我必须显示 2 种渲染,一种带有 css,另一种不带 css

class SearchSection extends Component {
  constructor(props) {
    super(props);
    this.state = {
      input: null,
      pathName: "/rule-builder"
    };
  }

  handleChange = e => {
    e.preventDefault();
    this.setState({ input: e.target.value });
  };

  render() {
    const handlepathName = window.location.pathname;
    console.log(handlepathName);

    return (
      <div>
        <div className="search-section">
          <input
            type="text"
            className="form-control"
            placeholder={this.props.placeholder || "Search lists of values ..."}
            value={this.state.input}
            onChange={this.handleChange}
          />
          <span className="search-icon">
            <img src={images.SEARCH_ICON} alt="icon" title="search" />
          </span>
        </div>
        <div className="category-scroll">
          {this.props.render && this.props.render(this.state.input)}
        </div>
      </div>
    );
  }
}

export default SearchSection;

我想有条件地渲染,如果页面不匹配那个链接我有这个&lt;div className="category-scroll"&gt;的渲染页面,如果它匹配然后没有&lt;div className="category-scroll"&gt;这行

【问题讨论】:

  • 您的问题不够清晰。你能说得更具体点吗?
  • 现在可以了吗?

标签: css reactjs bootstrap-4


【解决方案1】:

条件渲染包含一个条件和两个不同的 UI,这取决于条件是真还是假。 我举个例子:

 class SearchSection extends Component {
  constructor() {
    super();
    this.state = {
      pathName: "/rule-builder"
    };
  }

  render() {
    window.location.pathname == this.state.pathName  ? 
    return (
      <div>
        Hello
      </div>
    ) 
     :
     return (
      <div>
       good bye
      </div>
    )
  }
}

export default SearchSection;

【讨论】:

  • 在 return 语句中看到表达式错误
【解决方案2】:

这是有效的答案

    <div>
    <div className="search-section">
      <input
        type="text"
        className="form-control"
        placeholder={this.props.placeholder || "Search lists of values ..."}
        value={this.state.input}
        onChange={this.handleChange}
      />
      <span className="search-icon">
        <img src={images.SEARCH_ICON} alt="icon" title="search" />
      </span>
    </div>
    {window.location.pathname == this.state.pathName ? (
      <div>{this.props.render && this.props.render(this.state.input)}</div>
    ) : (
      <div className="category-scroll">
        {this.props.render && this.props.render(this.state.input)}
      </div>
    )}
  </div>

【讨论】:

    猜你喜欢
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2019-03-25
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多