【发布时间】:2021-08-01 14:16:27
【问题描述】:
我目前正在尝试使用 React,我正在尝试根据用户输入的内容更改 div 的背景颜色。除了 App 组件之外,我已经创建了一个带有按钮的输入元素的输入组件,但是我无法在没有我预期的 onChange 事件的情况下输入输入元素。我不确定如何通过单击按钮而不是 onChange 事件来更改状态变量(App.js 中的“颜色”)的状态。
我的 App.js
const AppDiv = styled.div
`margin: 0;
box-sizing: border-box;
display: flex;
width: 100%;
`
class App extends Component {
state = {
color: ' ',
name: null
}
colorchange = (event) => {
event.preventDefault();
this.setState({
color: event.target.value
})
}
render(){
return (
<AppDiv>
<Input
name = {this.state.name}
colour = {this.state.color}
colourChange = {this.colorchange}
Changecolour = {this.changecolour}
/>
</AppDiv>
)
}
}
Input.js
const ColorButton = styled.button
`
width: 100px;
height: 50px;
border-radius: 24px/50%;
background-color: green;
margin: 10px;
`
const ColorDiv = styled.div
`
height: 100vh;
flex-basis: 300px;
background-color: ${props => props.colour}; //Changing background with 'colour' prop
`
const input = (props) => {
return (
<ColorDiv>
<h2>What is your name</h2>
<input type = "text" value = {props.name}/>
<h2>Choose your colour</h2>
<input type = "text" value = {props.colour} />
<ColorButton onClick = {props.colourChange}> Change Colour </ColorButton>
</ColorDiv>
)
}
我正在使用 styled-components 来应用样式。任何建议或帮助将不胜感激。谢谢
【问题讨论】: