我希望我的按钮在点击时添加加载动画类,并在请求完成后删除该类。我正在使用bulma css,它有'is-loading'类用于加载动画。
我已经用这段代码实现了我想要的东西,但我不确定这是否是这种做法的“反应方式”。这是我做的:
class App extends React.Component {
constructor () {
super()
this.state = {
users: [],
isLoading: false
}
}
toggleLoading = () => {
this.setState((prevState, props) => ({
isLoading: !prevState.isLoading
}))
}
getUsers = () => {
this.toggleLoading()
let url = 'https://jsonplaceholder.typicode.com/'
fetch(url + 'users')
.then((res) => res.json())
.then((data) => {
this.setState({ users: data })
this.toggleLoading()
})
}
render () {
return (
<div className='section'>
<h1 className='title'>User List</h1>
<Button className={ 'button is-primary' + (this.state.isLoading ? ' is-loading' : '') } action={ this.getUsers } title='Get Users' />
<ul>
{
this.state.users.map((user) => <li className='subtitle'>{ user.name }</li>)
}
</ul>
</div>
)
}
}
const Button = (props) => (
<button
className={ props.className }
onClick={ props.action }
>
{ props.title }
</button>
)
ReactDOM.render(<App/>, document.getElementById('root'))
<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.1/css/bulma.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='root'></div>
答案 0 :(得分:2)
你做得对。如果你想改进它,你可以
loading
属性