我正在嘗試使用行內樣式移動單個組件,因為我希望它們位于網站的不同位置。為什么這段代碼不起作用?
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;
uj5u.com熱心網友回復:
所以這是一個代碼沙箱,其中包含基于您的代碼的作業示例-
https://codesandbox.io/s/strange-borg-hd2o4?file=/src/App.js
首先,position: absolute如果您要使用left: 200px. 當它是position: relative,沒有任何影響。
其次,設定這些樣式的更好方法是使用您已經創建的 id,然后將其作為 prop 傳遞給組件,查看示例。
第三,React 類組件即將淘汰——你應該首先學習 React 函式方法。我推薦https://fullstackopen.com/en/。
希望這一切都有意義!
uj5u.com熱心網友回復:
行內樣式通過屬性 name 傳遞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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/361747.html
標籤:javascript css 反应
下一篇:一維numpy陣列的高級切片
