【问题标题】:Using CSS transform: translate(...) with ReactJS使用 CSS 转换:translate(...) 和 ReactJS
【发布时间】:2015-12-14 13:57:34
【问题描述】:

根据https://facebook.github.io/react/tips/inline-styles.html

CSS 样式需要作为对象传递给组件。但是,如果您尝试使用变换样式,则会出现错误。

【问题讨论】:

  • 能否添加代码示例和错误信息?
  • React 显然是在默默地对错误的 css 做出反应,我缺少围绕我的比例值的括号
  • 对我来说同样如此,我有 transform: "translate(-50%, -50%);" 并注意到样式没有区别,直到我注意到这是由 ; 引起的

标签: reactjs css-transforms


【解决方案1】:

翻译也不适合我。我通过在 var 后面添加“px”来修复它。

ES6 代码:

render() {
    const x = 100;
    const y = 100;
    const styles = { 
        transform: `translate(${x}px, ${y}px)` 
    };

    return (
        <div style={styles}></div>
    );
}

【讨论】:

  • React 没有在这方面发出错误并不令人敬畏,它只是默默地失败。感谢您的正确回答。
  • 但这并没有采用-webkit-transform
【解决方案2】:

我的解决方案是首先连接字符串,然后将其传递给对象。注意这里使用了“px”。

render: function() {

    var cleft = 100;
    var ctop = 100;
    var ctrans = 'translate('+cleft+'px, '+ctop+'px)';
    var css = {
        transform: ctrans 
    }

    return ( 
        <div style={css} />
    )
}

【讨论】:

    【解决方案3】:

    如果上述解决方案不起作用,您还可以尝试以不同的方式格式化转换:

    render() {
        const xPx = 50;
        const yPercent = 50;
        return <div style={{transform: `translateX(${xPx}px) translateY(${yPercent}%)`}}></div>
    }
    

    【讨论】:

      【解决方案4】:

      这对我有用:

       transform: 'translateX(-100%)',
      

      【讨论】:

        【解决方案5】:

        您可以使用 translate 作为属性,react 提供所有翻译而不指定转换

        style={{
          position: "fixed",
          bottom: "0px",
          left: "50%",
          maxWidth:'450px',
          zIndex: 1,
          translateX:'-50%'
        }}
        

        【讨论】:

          【解决方案6】:

          这可以使用字符串模板文字 ` 作为转换键的值来完成:

          const styles = {
          logo: {
              transform: `translateX(20px)`
          },
          
          function Navbar() {
              return (
                  <nav style={styles.nav}>
                      <div style={styles.wrapper}>
                          <p className="logo" style={styles.logo}>Hello</p>
                      </div>
          

          有关模板文字的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2020-09-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-03-27
            • 1970-01-01
            • 2020-04-02
            相关资源
            最近更新 更多