Props

React Props

Component Properties

Function as Prop
1
const Foo = ({ hello }) => {
2
return hello('foo');
3
};
4
5
const hello = name => {
6
return <div>`hello from ${name}`</div>;
7
};
8
9
<Foo hello={hello} />;
Copied!
Component Injection
1
class WindowWidth extends React.Component {
2
constructor(props) {
3
super(props);
4
this.state = { width: 0 };
5
}
6
7
8
...
9
10
11
render() {
12
13
14
const { width } = this.state;
15
const { Width } = this.props;
16
return <Width width={width} />;
17
}
18
}
19
20
21
<WindowWidth Width={DisplayWindowWidthText} />
22
23
24
25
const DisplayDevice = ({ width }) => {
26
let device = null;
27
if (width <= 480) {
28
device = 'mobile';
29
} else if (width <= 768) {
30
device = 'tablet';
31
} else {
32
device = 'desktop';
33
}
34
return <div>you are using a {device}</div>;
35
};
Copied!

Prop Validation

children

渲染回调

渲染回调(Render Callback)即指那些子元素为某个函数的组件,也就是所谓的 Function-as-Child;我们可以利用这种模式复用有状态组件从而共享部分业务逻辑。如果需要定义渲染回调,则需要在 render 函数中返回对于传入的子元素的调用结果:
1
import { Component } from 'react';
2
3
class SharedThing extends Component {
4
// ...
5
6
render() {
7
return this.props.children(thing1, thing2);
8
}
9
}
10
11
export default SharedThing;
Copied!
然后在其他组件中我们可以调用该组件并且获得该组件的执行结果:
1
import React from 'react'
2
3
const AnotherComponent = () => (
4
<SharedThing>
5
{(thing1, thing2) => (
6
// use thing1 and thing2
7
)}
8
</SharedThing>
9
)
10
11
export default AnotherComponent
Copied!
一个比较典型的案例就是共享开关逻辑,某个开关组件 Toggle 会在内部存放用来表示当前开关状态的 toggled 变量,我们可以通过渲染回调的模式在将控制开关的逻辑提取出来:
1
import { Component } from 'react';
2
3
class Toggle extends Component {
4
state = {
5
isOpen: false
6
};
7
8
handleToggleClick = () => {
9
this.setState({
10
isOpen: !this.state.isOpen
11
});
12
};
13
14
render() {
15
return this.props.children(this.state.isOpen, this.handleToggleClick);
16
}
17
}
18
19
export default Toggle;
Copied!
现在所有使用 Toggle 的组件都能够访问到内部的 isOpen 状态并且能够使用 handleToggleClick 函数来触发 Toggle 内部状态的变化:
1
import React from 'react';
2
import Toggle from './Toggle';
3
4
const Accordion = ({ teaser, details }) => (
5
<Toggle>
6
{(isOpen, handleToggleClick) => (
7
<section>
8
<a onClick={handleToggleClick}>{`${isOpen ? '-' : '+'} ${teaser}`} </a>
9
{isOpen && details}
10
</section>
11
)}
12
</Toggle>
13
);
14
15
export default Accordion;
Copied!
1
const Thumbnail = ({ src, teaser }) => (
2
<Toggle>
3
{(isOpen, handleToggleClick) => (
4
<div>
5
<div>{teaser}</div>
6
<img
7
src={src}
8
alt={teaser}
9
onClick={handleToggleClick}
10
style={{
11
maxWidth: isOpen ? '100%' : 150
12
}}
13
/>
14
</div>
15
)}
16
</Toggle>
17
);
18
19
export default Thumbnail;
Copied!

cloneElement

Last modified 2yr ago