繁体   English   中英

内联样式化单个 React 组件

[英]Inline Styling Individual React Components

我正在尝试使用内联 styles 移动单个组件,因为我希望它们位于网站的不同位置。 为什么这段代码不起作用?

import "./App.css";
import React from "react";
import Window from "./components/Window";

class App extends React.Component {
  render() {
    return (
      <div className="App">
        <Window
          id="firstWindow"
          style={{ position: "relative", left: "200px" }}
          number={"1"}
        />
        <Window id="secondWindow" number={"2"} />
        <Window id="thirdWindow" number={"3"} />
      </div>
    );
  }
}

export default App;

此代码适用于应用程序的不同部分

import React from "react";
import "./Window.css";

class Window extends React.Component {
  render() {
    return (
      <div
        className="square"
        style={{ position: "relative", left: "200px" }}
      >
        {this.props.number}
      </div>
    );
  }
}

export default Window;

因此,这是一个代码沙箱,其中包含基于您的代码的工作示例-

https://codesandbox.io/s/strange-borg-hd2o4?file=/src/App.js

首先,你需要使用position: absolute如果你要使用left: 200px 当它是position: relative时,没有效果。

其次,设置这些样式的更好方法是使用您已经创建的 id,然后将其作为道具传递给组件,查看示例。

第三,React class 组件即将淘汰 - 你应该首先学习 React function 方法。 我推荐https://fullstackopen.com/en/

希望这一切都说得通!

内联样式通过属性名称style传递,使用它来设置组件中的样式。

style={ this.props.style }

一个演示:

 class App extends React.Component { render() { return ( <div className="App"> <Window id="firstWindow" style={{ position: "relative", left: "200px" }} number={"1"} /> <Window id="secondWindow" style={{ position: "relative", left: "100px" }} number={"2"} /> <Window id="thirdWindow" style={{ position: "relative", left: "10px" }} number={"3"} /> </div> ); } } class Window extends React.Component { render() { return ( <div className="square" style={ this.props.style } > {this.props.number} </div> ); } } // ======================================== ReactDOM.render( <App />, document.getElementById('root') );
 .square { background: #fff; border: 1px solid #999; float: left; font-size: 24px; font-weight: bold; line-height: 34px; height: 34px; margin-right: -1px; margin-top: -1px; padding: 0; text-align: center; width: 34px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM