比如我们要定义一个计数器 Counter,它包含一个 label 和一个 button,计数器的初始值由外部传入,点击 button 计数加 1:
这虽然是个简单组件,但却包含了 React 定义组件的两大核心点:
组件样式:
// counter样式
const counterStyle = {
backgroundColor: "orange",
width: "100px",
height: "100px",
borderRadius: "10px",
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
} as React.CSSProperties;
使用组件:
<Counter initialCount={6} />
// 属性
type Props = {
// 初始count
initialCount: number;
};
// 状态
type State = {
count: number;
};
// 计数器
class Counter extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
count: props.initialCount,
};
}
render() {
return (
<div style={counterStyle}>
<p>count={this.state.count}</p>
<button
onClick={() => {
this.setState({
count: this.state.count + 1,
});
}}
>
加 1
</button>
</div>
);
}
}
// 属性
type Props = {
// 初始count
initialCount: number;
};
// 计数器
function Counter(props: Props) {
const [count, setCount] = useState(props.initialCount);
return (
<div style={counterStyle}>
<p>count={count}</p>
<button
onClick={() => {
setCount(count + 1);
}}
>
加 1
</button>
</div>
);
}
注:此函数返回的类型是 JSX.Element
。
// 属性
type Props = {
// 初始count
initialCount: number;
};
// 计数器
const Counter = (props: Props) => {
const [count, setCount] = useState(props.initialCount);
return (
<div style={counterStyle}>
<p>count={count}</p>
<button
onClick={() => {
setCount(count + 1);
}}
>
加 1
</button>
</div>
);
};
注:此函数返回的类型是 JSX.Element
。
若需要,可以指定函数返回的具体类型:
// 属性
type Props = {
// 初始count
initialCount: number;
};
// 计数器
const Counter: React.FC<Props> = (props) => {
const [count, setCount] = useState(props.initialCount);
return (
<div style={counterStyle}>
<p>count={count}</p>
<button
onClick={() => {
setCount(count + 1);
}}
>
加 1
</button>
</div>
);
};
此时函数的返回值类型是 React.FC
。