官术网_书友最值得收藏!

Default JSX properties

TypeScript 3 has also improved how we can set default properties on React components with --strictNullChecks. Before TypeScript 3, we had to set properties that had default values as optional and perform null checks when referencing them. We haven't introduced React yet in this book, so we'll only touch on this briefly at this point.

Let's look through an example to get a feel for the improvement:

  1. The following is a React component with some default properties in TypeScript 2.9. The component is called SplitText and it takes in some text, splits it, and renders the bits that have been split in a list:
interface IProps {
text: string;
delimiter?: string;
}

class SplitText extends Component<IProps> {
static defaultProps = {
delimiter: ","
};
render() {
const bits = this.props.text.split(this.props.delimiter!);
return (
<ul>
{bits.map((bit: string) => (
<li key={bit}>{bit}</li>
))}
</ul>
);
}
}

const App = () => (
<div>
<SplitText text="Fred,Jane,Bob" />
</div>
);

export default App;

The component has a delimiter property that defaults to ",". In TypeScript 2.9, we need to make delimiter an optional property, otherwise we get a compiler error if we don't specify it in the calling component (even though there is a default).

Also notice that we need to put a ! after we reference delimiter in the bits variable declaration. This is to tell the compiler that this will never be undefined.

  1. Here's the component that calls SplitText:
const App = () => (
<div>
<SplitText text="Fred,Jane,Bob" />
</div>
);

  Here's what it looks like when rendered:

  1. Now, let's look at the component in TypeScript 3:
interface IProps {
text: string;
delimiter: string;
}

class SplitText extends React.Component<IProps> {
static defaultProps = {
delimiter: ","
};
render() {
const bits = this.props.text.split(this.props.delimiter);
return (
<ul>
{bits.map((bit: string) => (
<li key={bit}>{bit}</li>
))}
</ul>
);
}
}

Notice that we didn't need to make the delimiter property optional. Also notice that we didn't need to tell the compiler that this.props.delimiter can't be undefined.

So, in summary, we don't have to fiddle around to make default properties work nicely in TypeScript 3!

This is our first taste of React. Don't worry if the code examples don't make much sense at this point. We'll start to learn about React components in Chapter 3, Getting Started with React and TypeScript.

主站蜘蛛池模板: 马尔康县| 湖口县| 尚义县| 卢湾区| 沙雅县| 韩城市| 高邑县| 大竹县| 凌海市| 鹤山市| 永吉县| 成武县| 图木舒克市| 庆阳市| 荥阳市| 民乐县| 蕉岭县| 阳高县| 大邑县| 安国市| 淮滨县| 甘洛县| 太康县| 锦屏县| 元朗区| 五台县| 禹城市| 清流县| 海原县| 延庆县| 西乡县| 安西县| 泸水县| 天等县| 阿尔山市| 沙河市| 乃东县| 常山县| 海伦市| 平谷区| 固阳县|