【发布时间】:2017-12-28 06:50:35
【问题描述】:
我对 React 环境比较陌生。我为书签功能编写了一个非常基本的组件。
基本点击favourite icon,
it sends an ajax call > create a record in the db > on ajax success show a flash message "Page added to favourites."
它是一个切换按钮,所以再次点击它时,
it sends an ajax call > delete the record in the db > on ajax success i show a flash message "Page removed from favourites."
这是我编写的完美运行的组件。但我不喜欢的是,使用setTimeOut 函数隐藏flash 消息。我觉得必须有其他方式(可能是 css)才能以 React 方式实现同样的效果。
import React, {
PropTypes
} from 'react';
import {
Component
} from 'aplus-base';
import axios from 'axios';
const API = "http://localhost:3000/favourites/toggle"
const API2 = "http://localhost:3000/favourites/current_bookmark_status"
@Component
export default class Bookmark extends React.Component {
static styles = require('./bookmark.sass')
state = {
bookmarked: '',
message: "",
alert: false
}
componentDidMount() {
this.fetchData();
}
toggle() {
const querystring = require('querystring')
axios.post(API, querystring.stringify({
current_page_key: '/marketing'
}), {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
})
.then(response => {
this.setState({
bookmarked: response.data.bookmarked,
alert: true
});
const message = response.data.bookmarked ? "Added to Favourites" : "Removed from Favourites"
this.setState({
message
})
setTimeout(() => {
this.setState({
alert: false
});
}, 2000);
})
}
fetchData = () => {
const querystring = require('querystring')
axios.post(API2, querystring.stringify({
current_page_key: '/marketing'
}), {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
})
.then(response => {
this.setState({
bookmarked: response.data.bookmarked
});
})
}
render() {
return ( <
div >
<
i className = {
this.state.bookmarked ? "icon icon-bookmarked" : "icon icon-bookmark"
}
onClick = {
this.toggle.bind(this)
}
/> <
div styleName = {
`result ${this.state.alert ? "alert-shown": "alert-hidden"}`
} > {
this.state.message
} <
/div> <
/div>
)
}
}
.icon display: inline-block width: 30px height: 30px background: no-repeat center background-size: contain vertical-align: middle &.icon-bookmark background-image: url(../assets/bookmark.png) transition: all 1s linear &.icon-bookmarked background-image: url(../assets/bookmarked.png) transition: all 1s linear .result position: fixed top: 0 left: 40% width: 20% box-sizing: border-box padding: 4px text-align: center font-weight: bold .alert-shown opacity: 1;
transition: all 250ms linear;
.alert-hidden opacity: 0;
transition: all 250ms linear;
<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>
【问题讨论】:
标签: javascript ajax css reactjs