[英]React rerender animation on state change
i'm using Animate css in my project, and i have a form where a user should provide an answer to a question. 我在我的项目中使用Animate css ,并且具有用户应提供问题答案的表单。 If an answer is correct word
correct
should be faded in and wrong
in opposite case. 如果答案是正确的单词
correct
应该褪去并wrong
在相反的情况下。 Here is a working simplified example of my code. 这是我的代码的一个简化工作示例。
Stateful component: 有状态组件:
import React, { Component } from 'react'
import FormCheckIfCorrect from './FormCheckIfCorrect'
class Form extends Component {
constructor(props) {
super(props)
this.state = {
correct: '5',
userInput: '',
userAnswer: ''
}
}
handleChange = (e) => {
this.setState({ userInput: e.target.value })
}
handleSubmit = (e) => {
e.preventDefault();
this.setState({ userAnswer: '' }, () => {
this.setState({ userAnswer: this.state.userInput })
})
}
render() {
return (
<div>
<p>2 + 3 = ? </p>
<form onSubmit={this.handleSubmit}>
<input type='number' value={this.state.userInput} onChange={this.handleChange} />
<button >Submit</button>
</form>
{this.state.userAnswer !== '' ? <FormCheckIfCorrect userAnswer={this.state.userAnswer} correct={this.state.correct} /> : ''}
</div>
)
}
}
export default Form
Functional component: 功能组件:
import React from 'react'
const FormCheckIfCorrect = (props) => {
let result = props.userAnswer === props.correct ? <p className="animated fadeIn">correct</p> : <p className="animated fadeIn">wrong</p>
return result
}
export default FormCheckIfCorrect
My question is about this part of my code : 我的问题是关于我的代码的这一部分:
handleSubmit = (e) => {
e.preventDefault();
this.setState({ userAnswer: '' }, () => {
this.setState({ userAnswer: this.state.userInput })
})
}
In order to achieve the fade in effect each time a user clicks Submit button i set userAnswer
to nothing, and then in callback i set it again to userInput
. 为了每次用户点击提交按钮即可实现淡入效果我设置
userAnswer
不了了之,然后在回调,我再次将其设置为userInput
。 It works(don't forget to include animate css), but i don't think it's a right way to do it. 它有效(不要忘了包括动画css),但是我不认为这是正确的方法。 I'd appreciate if someone could tell me how to do it right.
如果有人能告诉我正确的做法,我将不胜感激。
You can refactor your component FormCheckIfCorrect 您可以重构组件FormCheckIfCorrect
const FormCheckIfCorrect = ({ userAnswer, correct }) => (
<p className="animated fadeIn">
{ userAnswer === correct ? 'correct' : 'wrong' }
</p>
)
This way you don't repeat yourself by adding same p tags with duplicated class. 这样,您不会通过添加具有重复类的相同p标签来重复自己。 Instead, we only change the content of the paragraph
相反,我们只更改该段的内容
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.