【问题标题】:Trying to hide <p> tags by default with state react es6尝试使用 state react es6 默认隐藏 <p> 标签
【发布时间】:2017-07-30 15:56:00
【问题描述】:

我有以下静态视图:

import React from 'react';

export default class Champ extends React.Component {
  render() {
    return (
      <div>
        <img src={this.props.champ.file} />
        <p>Name: {this.props.champ.name } </p>
        <p>Role: { this.props.champ.role } </p>
        <p>Difficulty: { this.props.champ.diff } </p>
        <p>Price: { this.props.champ.price } </p>
      </div>
    )
  }
}

我想更改它,以便在加载页面时只有图像可见,并且当它们悬停在信息上时会淡入。

我想通过让所有包含信息的&lt;p&gt; 标签在页面打开时默认隐藏并使用状态来做到这一点。

我想我可以做一些事情,比如把它们变成一个常量

const x = <p>Name: {this.props.champ.name } </p>
    <p>Role: { this.props.champ.role } </p>
    <p>Difficulty: { this.props.champ.diff } </p>
    <p>Price: { this.props.champ.price } </p>


this.state = { x.style.visibilty = 'hidden'};

}

但我实际上不确定如何执行此操作。我现在才学习状态,以前从未使用过隐藏。谢谢。

【问题讨论】:

  • State 应该写成这样this.state = { visible: true },如果this.state.visible === true,只需创建一个渲染所有p标签的函数
  • @Raymond 的建议应该可以正常工作

标签: javascript css reactjs ecmascript-6


【解决方案1】:

State 应该表达状态,但不保存渲染的内容。因此,您只需要一个detailsVisible 标志或其他状态,您可以使用setState({ detailsVisible: true | false }) 切换onMouseEnteronMouseLeave,然后您可以使用this.state.detailsVisible 来渲染&lt;p&gt; 标签或不渲染。要将它们一起显示和隐藏,将它们放在包装元素或组件中并使用表达式切换它的可见性会很方便:

class Champ extends React.Component {
  state = { detailsVisible: false };
  handleMouseEnter = e => this.setState({ detailsVisible: true });
  handleMouseLeave = e => this.setState({ detailsVisible: false });
  render() {
    return (
      <div onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>
        <img src={this.props.champ.file} />
        { this.state.detailsVisible && <ChampDetails champ={this.props.champ} /> }
      </div>
    )
  }
}

const ChampDetails = ({champ}) => (
  <div>
    <p>Name: { champ.name } </p>
    <p>Role: { champ.role } </p>
    <p>Difficulty: { champ.diff } </p>
    <p>Price: { champ.price } </p>
  </div>
);

^ 需要 class properties,否则将类属性分配(statehandleMouseEnterhandleMouseLeave)放在构造函数中。

【讨论】:

  • 谢谢你这实际上现在更有意义了,我试图在
  • @matthewg 您可以使用&lt;img onMouseOver={e =&gt; this.setState(...)} /&gt;,但通常建议像我的示例一样创建处理函数。无论哪种方式,要理解的重要部分是,onMouseOver 等处理程序属性应该是对函数的引用,而不是像onMouseOver={this.setState(...)} 这样的函数调用或任何任意 JS 代码。
  • @matthewg 请马克回答问题:)
猜你喜欢
  • 2012-03-09
  • 2019-10-13
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多