【问题标题】:Render css class in image tag in react在 React 中的图像标签中渲染 css 类
【发布时间】:2016-09-04 14:15:16
【问题描述】:

我正在用 React 制作一个应用程序,我希望在单击按钮后旋转和翻译图像。

render: function() {
    var imageSrc = this.props.imageSrc;
    var rotate = this.props.rotate;
    var translate = this.props.translate;
    var opacity = this.props.opacity;
    var scale = this.props.scale;
 
    return (
      <div>
        <img src={imageSrc} tyle={{opacity: opacity? 0.5:1,height: scale? 600:300, width: scale? 800:400}}/>
        <div>
          <input type="file" onChange={this.handleChangeFile} />
        </div>
      </div>
    );
  }
});

我在 style 标签中设置了 opacity 和 scale 属性,但我不知道如何添加旋转和翻译,因为它们没有 html 标签。

所以我在 JXS 之外创建了一个变量, var imageRotate; 如果({旋转}===真){ className='rotator'}

  return (
    <div>
     <img src={imageSrc} style={{className={imageRotate}/>
    <div>

但它不起作用。我想知道将 css 传递到图像标签的最佳方法是什么?

【问题讨论】:

    标签: javascript css reactjs frontend


    【解决方案1】:

    以一种反应的方式,我建议将关注点分开:

    • 在 css 中制作前后样式(而不是在 react 中使用内联样式),并将变换、旋转等放在后类中。
    • 在您的反应代码中,将点击处理程序添加到您的 &lt;img&gt;,它将新类应用于您的 &lt;img&gt; 组件

    示例代码(每次单击时都会更改类)如下所示:

    class Application extends React.Component {
      constructor(props) {
        super(props);
        this.state={ className: 'class1' }
      }
      handleClick() {
        this.setState({
          className: (this.state.className=='class1')? 'class2' : 'class1'
        })
      }
      render() {
        return <div>
          <p className={this.state.className} 
             onClick={() => this.handleClick()}>
               click me to change color
          </p>
        </div>;
      }
    }
    

    在本例中,class1 或 class2 应用于 &lt;p&gt; 元素,但原理相同。

    Working codepen here.

    【讨论】:

      【解决方案2】:

      平移和旋转是 CSS transform 属性的一部分。您可以像任何其他 CSS 一样在样式中设置 transform。

      例如,要处理基本的 React JSfiddle:

      var Hello = React.createClass({
        render: function() {
          return <div style={{transform:"translate(10px, 10px) rotate(-15deg)"}}>Hello {this.props.name}</div>;
        }
      });
      
      ReactDOM.render(
        <Hello name="World" />,
        document.getElementById('container')
      );
      

      见 jsfiddle:https://jsfiddle.net/a02jkshm/

      【讨论】:

        猜你喜欢
        • 2010-11-30
        • 2018-02-21
        • 1970-01-01
        • 1970-01-01
        • 2013-10-11
        • 2020-06-15
        • 1970-01-01
        • 2019-05-17
        • 1970-01-01
        相关资源
        最近更新 更多