我已经处理这个问题好几天了。我只是不明白为什么元素的样式没有改变,我可以看到事件处理程序正在工作,点击改变了"this.style“,但它不适用于元素。
import { getByPlaceholderText } from '@testing-library/dom';
import React from 'react';
import {Component} from 'react';
import Element from '../Element/Element'
class Element extends Component{ // element who has the eventLister click
render(){
return <div onClick = {this.props.func} style = {this.props.style}>
HELLO
</div>
}
}
class UserInput extends Component{ // here in UserInput I am returning "Element" above
// and i am sending the event handler and style as
// props
style = {
color:'red',
fontSize:'40px'
}
func2=()=>{
this.style = ({
color:'black',
});
console.log('clicked')
console.log(this.style);
}
render(){
return < Element func = {this.func2.bind(this)} style= {this.style}/>
}}
export default UserInput;发布于 2021-04-19 16:26:35
更改this.style不会触发重新呈现,因此Element组件看不到新样式。您应该将样式放在component state this.state = { style: ... }中
并在func2内部更新状态this.setState({ style: ... })
然后是render函数:
render(){
return < Element func = {this.func2.bind(this)} style= {this.state.style}/>
}https://stackoverflow.com/questions/67158363
复制相似问题