我希望不显示任何元素。所以我在React元素中使用内联样式进行显示:无。然后,在setTimeout运行之后,显示将转到一个空字符串,以便显示我的内容。但是我的显示始终是一个空字符串。状态不会传递给内联样式,因此永远不会分配值none。如何将状态传递给内联样式?
我尝试了style={{display:`${this.state.hidden}`}}
和style={{display: this.state.hidden}}
class Home extends Component{
state={
hidden: 'none'
}
showHello=()=>{
this.setState({
hidden: ''
})
}
showName=()=>{
this.setState({
hidden: ''
})
}
showFullStack=()=>{
this.setState({
hidden: ''
})
}
componentDidMount(){
setTimeout(()=>this.showHello(), 2500);
setTimeout(() => this.showName(), 20000);
setTimeout(() => this.showFullStack(), 10000);
}
render(){
return(
<div className='home-div'>
<h2 className='hello-header' style={{display:`${this.state.hidden}`}}>Hello, I'm</h2>
<h2 className='name-header' style={{display:`${this.state.hidden}`}}>Sean</h2>
<h2 className='full-stack-header' style={{display: this.state.hidden}}>I'm a Full Stack Web Developer.</h2>
<a className='resume'>Download my resume here!</a>
<a className='github'>View my GitHub here!</a>
<h1 className='arrow'>⇩</h1>
</div>
感谢您的帮助,我对React还是有些陌生,因此,如果这是新手的错误,请原谅我。
谢谢!
答案 0 :(得分:0)
尝试一下:您的代码将起作用。
render(){
const { hidden } = this.state;
return(
<div className='home-div'>
<h2 className='hello-header' style={{ display: hidden }}>Hello, I'm</h2>
<h2 className='name-header' style={{ display: hidden }}>Sean</h2>
<h2 className='full-stack-header' style={{ display: hidden }}>I'm a Full Stack Web Developer.</h2>
<a className='resume'>Download my resume here!</a>
<a className='github'>View my GitHub here!</a>
<h1 className='arrow'>⇩</h1>
</div>
)}
}
答案 1 :(得分:-1)
如果要有条件地显示项目,我将使用一个数组并检查该值。
See it live!
const displayMap = {
false: 'none',
true: 'block'
}
class Home extends Component {
state = {
display: []
}
showMessage = (name) => {
this.setState({
display: [...this.state.display, name]
})
}
componentDidMount(){
setTimeout(()=> this.showMessage('hello'), 2500);
setTimeout(() => this.showMessage('name'), 20000);
setTimeout(() => this.showMessage('full-stack'), 10000);
}
render(){
const { display } = this.state
return(
<div className='home-div'>
<h2 className='hello-header' style={{display: displayMap[display.indexOf('hello') >= 0]}}>Hello, I'm</h2>
<h2 className='name-header' style={{display: displayMap[display.indexOf('name') >= 0]}}>Sean</h2>
<h2 className='full-stack-header' style={{display: displayMap[display.indexOf('full-stack') >= 0]}}>I'm a Full Stack Web Developer.</h2>
<a className='resume'>Download my resume here!</a>
<a className='github'>View my GitHub here!</a>
<h1 className='arrow'>⇩</h1>
</div>
)
}
}