该react的速度插件提供已经实施react使用Velocity的动画组件。
我猜滚动功能也可以通过动画来实现,但是 Velocity 库有scroll 命令。我已经审查了速度react插件,它为动画提供了接口(组件)。不支持 Velocity 命令。
在 React 中使用 Velocity 命令非常容易。我已经根据您的问题创建了react-velocity-scroll 存储库,并且有一个以类似聊天的方式发送/列出消息的实时演示。
请注意,Velocity 库通过velocity-react 插件包含在示例中。推荐包含用于未来高级动画的插件,因为它提供了已经实现的 React 组件来使用 Velocity 的动画。但是 repo 不使用任何动画。它仅使用 Velocity 库的滚动命令。如果您愿意 - 您可以独立导入 Velocity 库。
但是,这是我的组件。请关注MessageItem组件 - 一旦添加了新消息,然后向下滚动到它。
应用程序
import React from 'react';
import MessagesList from './MessagesList';
const style = {
textAlign: 'center'
};
class App extends React.Component{
constructor(props) {
super(props);
this.state = {
/**
* @type Array - Store sent messages
*/
messages: [],
/**
* @type String - Store the input value.
* It's reset on message sent
*/
text: ''
}
}
handleOnChange(e) {
const text = e.target.value;
this.setState({ text });
}
handleOnKeyPress(e) {
const text = e.target.value;
// Send the message on `Enter` button press
if (e.key === 'Enter') {
this.sendMessage(text);
}
}
/**
* Add the message to the state and reset the value
* of the input
*
* @param String text - Message text
*/
sendMessage(text) {
const { messages } = this.state;
const message = { date: new Date(), text };
this.setState({
messages: messages.concat([message]),
text: ''
});
}
render() {
const { messages, text } = this.state;
return <div style={style}>
<h1>Please enter your text message:</h1>
<input
value={text}
placeholder="Press Enter for sending"
onChange={this.handleOnChange.bind(this)}
onKeyPress={this.handleOnKeyPress.bind(this)} />
<MessagesList messages={messages} />
</div>
}
}
export default App;
消息列表
import React from 'react';
import MessageItem from './MessageItem';
const style = {
height: '100px',
overflowY: 'scroll'
};
const MessagesList = (props) => {
let { messages } = props;
messages = messages.map( function(message, index){
return <MessageItem key={index} index={index} message={message} />
});
return <ul style={style}>{messages}</ul>
};
export default MessagesList;
消息项
import React from 'react';
import ReactDOM from 'react-dom';
const Velocity = require('../node_modules/velocity-react/lib/velocity-animate-shim');
const style = {
listStyle: 'none'
};
class MessageItem extends React.Component{
componentDidMount() {
const parentNode = ReactDOM.findDOMNode(this).parentNode;
const node = ReactDOM.findDOMNode(this);
// Once a new item is being added, then scroll down to it
Velocity(node, 'scroll', {
duration: 500,
container: parentNode,
queue: false
});
}
render() {
const { message } = this.props;
return <li style={style}>{message.date + ' - ' + message.text}</li>
}
}
export default MessageItem;