【发布时间】:2021-03-02 09:13:31
【问题描述】:
我想将 javascript 代码转换为 Reactjs。我如何在 React.js 中编写这种代码。帮我解释一下我是如何在 react.js 中做到这一点的。我还提到了我的反应代码,我在代码中做错了什么以及如何才能正确运行我的代码。
const select = document.querySelector('select');
const html = document.querySelector('html');
document.body.style.padding = '10px';
function update(bgColor, textColor) {
html.style.backgroundColor = bgColor;
html.style.color = textColor;
}
select.onchange = function() {
( select.value === 'black' ) ? update('black','white') : update('white','black');
}
<--Html--> This is Html Code which i want to convert it all in jsx file i React.js
<html>
<body>
<label for="theme">Select theme: </label>
<select id="theme">
<option value="white">White</option>
<option value="black">Black</option>
</select>
<h1>This is my website</h1>
</body>
</html>
我在代码中做错了什么以及如何正确运行我的代码。
import React from 'react';
import './App.css';
class App extends React.Component{
constructor(){
super();
this.state={
whether:'',
color:''
}
}
change=(event)=>{
this.setState({whether: event.target.value});
}
handleChange=(event)=>{
this.setState({color: event.target.value});
}
render(){
let pop=this.state.color;
return(
<div>
<label for="weather">Select the weather type today: </label>
<select id="weather" onChange={this.change} >
<option value="">--Make a choice--</option>
<option value="Its sunny Today">Sunny</option>
<option value="ITS Rainy Today">Rainy</option>
<option value="snowing">Snowing</option>
<option value="overcast">Overcast</option>
</select>
<label for="theme">Select theme: </label>
<select id="theme" onChange={this.handleChange} >
<option value="white">White</option>
<option value="black">Black</option>
</select>
<h1 style={{backgroundColor:{this.state.color}}} >{this.state.whether}</h1>
</div>
)
}
}
export default App;
【问题讨论】:
-
你可以转换,但在此之前你需要学习 Reactjs 才能轻松转换
-
其实我已经在学习 React.js 但我卡在这里,无法在 react.js 中转换这段代码
-
你没有提到你在反应中停留的地方
-
问题是什么?有错误信息吗?行为不正确?我们具体应该寻求哪些帮助?是不是背景颜色的问题?
-
是的,问题是当我运行代码时背景颜色没有改变。当我在下拉菜单中选择黑色时,我想这样做,h1 元素将其背景颜色更改为黑色。当我选择白色时,它会变为白色背景
标签: javascript html css reactjs web-frontend