使用import導入其它文件中的component:
import React from 'react';
import CustomButton from './CustomButton';
可以使用dot-notation來引用component:
import React from 'react';
const MyComponents = {
DatePicker: function DatePicker(props) {
return <div>Imagine a {props.color} datepicker here.</div>;
}
}
function BlueDatePicker() {
return <MyComponents.DatePicker color="blue" />;
}
自定義組件首字母必須大寫:
import React from 'react';
// Wrong! This is a component and should have been capitalized:
function hello(props) {
// Correct! This use of <div> is legitimate because div is a valid HTML tag:
return <div>Hello {props.toWhat}</div>;
}
function HelloWorld() {
// Wrong! React thinks <hello /> is an HTML tag because it's not capitalized:
return <hello toWhat="World" />;
}
可以通過變量引用組件:
// Wrong! JSX type can't be an expression.
return <components[props.storyType] story={props.story} />;
// Correct! JSX type can be a capitalized variable.
const SpecificStory = components[props.storyType];
return <SpecificStory story={props.story} />;
props默認為true:
<MyTextBox autocomplete />
<MyTextBox autocomplete={true} />
使用spread語法來賦值,例如下面兩個段代碼效果是一樣的:
function App1() {
return <Greeting firstName="Ben" lastName="Hector" />;
}
function App2() {
const props = {firstName: 'Ben', lastName: 'Hector'};
return <Greeting {...props} />;
}
可以將函數作為children,通過props.children來引用:
// Calls the children callback numTimes to produce a repeated component
function Repeat(props) {
let items = [];
for (let i = 0; i < props.numTimes; i++) {
items.push(props.children(i)); // 調用函數
}
return <div>{items}</div>;
}
function ListOfTenThings() {
return (
<Repeat numTimes={10}>
{(index) => <div key={index}>This is item {index} in the list</div>}
</Repeat>
);
}
React中什么是Uncontrolled Component?
好,這一節就到這里。后續我將介紹更多React技術細節,來慢慢解答上述問題。
想學計算機技術嗎?需要1對1專業級導師指導嗎?想要團隊陪你一起進步嗎?歡迎加我為好友!微信號:iTekka。