styled-components + form小问题

异常代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// 表单不能输入值
const SignUp = props => {
const Wrapper = styled.div`
border: 1px solid #f5f4f0;
max-width: 500px;
padding: 1em;
margin: 0 auto;
`;

const Form = styled.form`
label,
input {
display: block;
line-height: 2em;
}

input {
width: 100%;
margin-bottom: 1em;
}
`;

return (
<Wrapper>
<h2>Sign Up</h2>
<Form
onSubmit={...}
>
<label htmlFor="username">Username:</label>
<input />
<label htmlFor="email">Email:</label>
<input />
<label htmlFor="password">Password:</label>
<input />
<Button type="submit">Submit</Button>
</Form>
</Wrapper>
);
};

styled-components 部分的代码放在组件的外部,代码就正常了…

官方说明

It is important to define your styled components outside of the render method, otherwise it will be recreated on every single render pass. Defining a styled component within the render method will thwart caching and drastically slow down rendering speed, and should be avoided.

尤其在处理表单时,如果每输入一个字符就re-render组件,的确会很奇怪。