在react中的image标记中渲染css类

Render css class in image tag in react

本文关键字:css react 中的 image      更新时间:2023-09-26

我正在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>
    );
  }
});

我在样式标记中设置了不透明度和比例属性,但我不知道如何添加旋转和平移,因为它们没有html标记。

所以我在JXS之外做了一个变量,var imageRotate;if({rotate}==true){className='rotator'}

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

但它不起作用。我想知道将css传递到image标记中的最佳方式是什么?

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

  • 在css中创建before和after样式(不要在react中使用内联样式),并将transform、rotate等放在after类中
  • 在react代码中,向<img>添加一个单击处理程序,该处理程序将新类应用于<img>组件

示例代码(每次单击都会更改类)看起来像这样:

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>;
  }
}

在该示例中,class1class2被应用于<p>元件,但是原理是相同的。

在这里工作代码笔。

平移和旋转是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/