Mail.js
SendList.js
FriendList
# 案例:邮件发送-收件人选择
仿 QQ 邮箱发送邮件的添加接收人功能
```css
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
li {
line-height: 30px;
}
.fl {
float: left;
}
.fr {
float: right;
}
.clear:after {
content: '';
display: block;
clear: both;
}
.box {
padding: 10px;
margin: 10px;
border: 1px solid #000;
width: 200px;
}
.multi-input {
margin: 10px;
padding: 5px;
border: 1px solid #666;
}
.multi-input>div {
height: 30px;
}
```
```jsx
import React from 'react';
import './index.css';
import MultiInput from './MultiInput';
export default class GetDerviedStateFromPropsComponent extends React.Component {
constructor(...props) {
super(...props);
this.state = {
friends: [
{id: 1, name: '张三', email: 'zhangsan@email.com'},
{id: 2, name: '李四', email: 'lisi@email.com'},
{id: 3, name: '王五', email: 'wangwu@email.com'}
],
user: null
};
this.addUser = this.addUser.bind(this);
}
addUser(user) {
this.setState({user})
}
render() {
let {friends, user} = this.state;
return (
<div className="clear">
<h1>发送邮件</h1>
<hr/>
<ul className="box fl">
{
friends.map(friend => (
<li key={friend.id} onClick={e=>this.addUser(friend)}>
{friend.name}
</li>
))
}
</ul>
<div className="fl">
<MultiInput user={user} />
</div>
</div>
);
}
}
```
```jsx
import React from 'react';
import './index.css';
export default class MultiInput extends React.Component {
static defaultProps = {
user: []
}
constructor(...props) {
super(...props);
this.state = {
users: []
}
this.keyDown = this.keyDown.bind(this);
}
static getDerivedStateFromProps(props, state) {
if (props.user && !state.users.find(u => u.email === props.user.email)) {
let users = MultiInput.addNewUser(state.users, {name: props.user.name, email: props.user.email});
return {
users
}
}
return null;
}
keyDown({which, target}) {
if (which === 13 && target.value !== '') {
let users = MultiInput.addNewUser(this.state.users, {name: '', email: target.value});
this.setState({
users
});
target.value = '';
}
}
static addNewUser(users, user) {
if ( !users.find(u => u.email === user.email) ) {
users.push(user);
}
return users;
}
render() {
let {users} = this.state;
return (
<div className="multi-input">
{
users.map(user => (
<div key={user.email}>{user.name} {user.email};</div>
))
}
<div>
<input type="text" onKeyDown={this.keyDown} />
</div>
</div>
);
}
}
```
网友评论