【React】初学者指南总结 ✍🏻
React是一种库。
React 是一个声明式、高效且灵活的 JavaScript 库,用于构建用户界面。您可以通过组装称为“组件”的小而独立的部件来构建复杂的用户界面。
引入React
搭建React环境非常困难,需要精通Webpack、Babel或TypeScript等知识。这次我们尝试使用一个名为Create React App的工具来引入React?
Create React App可以简单地说是React开发环境的模板,无需复杂的配置即可轻松引入React的工具。
在终端执行以下命令:使用全局-g选项安装create-react-app。
sudo npm i -g create-react-app
使用 create-react-app 工具创建一个名为 sample-react 的项目
切换目录并启动服务器。使用ctrl + c停止服务器。
进入sample-react目录,并执行npm start。
请确认指令
让我们检查一下由create-react-app生成的package.json中可用的命令。
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
-
- start・・・開発用サーバーの立ち上げ。基本的にこのコマンドで開発を行なっていく。
-
- build・・・本番環境アップ用のスクリプトを生成。
-
- test・・・テストスクリプト。テストコードを流すためのコマンド
- eject・・・隠し設定の可視化をするコマンド。こちらのコマンドを叩くと、隠されていたconfigディレクトリなどの設定ファイルが表示される。
怎样使用style
使用JSX编写className属性,在导入CSS文件并进行样式设置。
import "./Example.css"; // cssファイルimport
const Example = () => {
return (
<div className="component"> // className属性付与
<h3>Hello Component</h3>
</div>
);
};
export default Example;
.component {
background: red;
}
组件的定义和划分方法
组件是在React中用于在屏幕上显示的部分。它们将显示所需的数据和处理等内容汇总为一个对象。通过使用这些组件进行构建,可以提高重用性和可读性,同时降低由于松耦合而导致的错误发生率。
组件定义
组件应该被定义为JavaScript函数。
这个函数组件应该用JSX来描述要显示的元素,并通过return语句返回。
通过将函数名的首字母大写,明确表示它是一个组件。
函数组件的定义
function Sample() {
return <h1>Hello</h1>;
}
组件的执行
<Sample>
在箭头函数中也是可行的。
const Sample = () => {
return <h1>Hello</h1>;
}
// 省略
const Sample = () => <h1>Hello</h1>;
如果JSX代码有多行,则需要用()括起来。
function Sample() {
return (
<div>
<h1>Hello</h1>
</div>
);
}
// アロー関数
const Sample = () => (
<div>
<h1>Hello</h1>
</div>
);
切割方式
定义一个函数组件并导出它。
在想要调用该函数组件的文件中导入并执行。
函数组件
const List = () => {
return (
<ul>
<li>item-1</li>
<li>item-2</li>
<li>item-3</li>
<li>item-4</li>
<li>item-5</li>
</ul>
);
};
export { List }; // 名前付きexport
// defaultexportする場合は下記
// export default List;
import { List } from "./components/List"; // 関数コンポーネントimport
// defaultexportをimportする場合は下記
// import List from "./components/List";
const Example = () => {
return (
<div className="component">
<h3>Hello Component</h3>
<List />
</div>
);
};
export default Example;

我认为在一个组件文件中基本上只需要描述一个组件,所以在这种情况下,不需要特意使用带有命名的导出,基本上可以使用默认导出的写法。
React Fragment 的使用方式
片段是指一小部分被分离或断裂的东西。
在 React 中,常见的一种模式是组件返回多个元素。通过使用片段(fragment),您可以将子元素组合在一起,而不会在 DOM 中添加额外的节点。
React 公式- React 公式
React组件必须具有一个根元素的限制。
根元素只有一个。
const Sample = () => {
return (
<div className="component">
<h3>Hello Component</h3>
<h3>Hello Fragment</h3>
<p>サンプルテキストサンプルテキストサンプルテキストサンプルテキストサンプルテキスト</p>
</div>
);
};
当根元素数量为三时会出现错误。
const Sample = () => {
return (
<div className="component">
<h3>Hello Component</h3>
</div>
<h3>Hello Fragment</h3>
<p>サンプルテキストサンプルテキストサンプルテキストサンプルテキストサンプルテキスト</p>
);
};

如果需要将根元素仅保留一个,但又不想创建仅用于将根元素减少至一个的元素时,可以使用React片段。
import React from "react"; // reactパッケージのdefaultインポート
const Sample = () => {
return (
<React.Fragment>
<div className="component">
<h3>Hello Component</h3>
</div>
<h3>Hello Fragment</h3>
<p>サンプルテキストサンプルテキストサンプルテキストサンプルテキストサンプルテキスト</p>
</React.Fragment>
);
};
实际生成的Elements中,React.Fragment部分将不会输出任何东西。
作为简写,仅使用<>也可以。
如果使用此简写,就不需要导入React。
顺便一提,据说在ReactNative中不能使用此简写。
在片段中,只能附加一个名为key的属性。
在JSX中执行JavaScript代码的方法是什么?
在jsx代码中,可以使用{}来评估js表达式并输出结果。
因此,在jsx的{}内部无法使用诸如for循环和if语句等的语句来进行return操作。
语句是指变量声明、for循环、if语句、switch语句或被分号分隔的东西
例: 我每天早上六点起床跑步。
import "./Sample.css";
const Expression = () => {
const title = "SampleTitle";
const arry = ["item1", "item2", "item3"];
const hello = (arg) => `${arg} Function`;
const jsx = <h3>こんにちは! JSX</h3>;
return (
<div className={title.toLowerCase()}>
<h3>Hello {title}!</h3>
<h3>{arry}</h3>
<h3>{hello("Hello")}</h3>
{/**コメント */}
{<h3>Hello JSX</h3>}
{jsx}
</div>
);
};
export default Expression;
.sampletitle {
color: red;
}

如果传递一个数组,它将自动展开并将其连接起来输出。
通过props将值传递给组件
函数组件接受形式参数,并在运行时通过描述属性,将其传递为实际参数。
import Child from "./components/Child";
const Example = () => <Child color="red" />;
export default Example;
const Child = (props) => {
console.log(props); // → {color: 'red'}
console.log(props.color); // → red
return (
<div className="component">
<h3>Hello Component</h3>
</div>
);
};
export default Child;
可以使用这个props来创建可重用的组件,将它们应用到className上。
const Child = (props) => {
return (
<div className={`component ${props.color}`}>
<h3>Hello Component</h3>
</div>
);
};
export default Child;
使用来运行上述组件时,class会变成component red,因此可以进行如下样式设置。
.component.red {
color: red;
border: 5px solid red;
}
/* <Child />のように属性を取らなければこちらのスタイルが当たる */
.component {
color: blue;
border: 5px solid blue;
}
const { color } = props;
return (
Hello Component
);
};
例子:
const Child = ({color = “green”}) => {
return (
你好组件
);
};
尝试通过props传递各种值
添加num属性并显示
import Child from "./components/Child";
const Example = () => <Child color="red" num={123} />;
export default Example;
import "./Child.css";
const Child = (props) => {
return (
<div className={`component ${props.color}`}>
<h3>Hello Component</h3>
<p>{props.num}</p>
</div>
);
};
export default Child;
在中文中,将函数hello作为fn属性添加并显示。
import Child from "./components/Child";
const Example = () => {
const hello = (arg) => `Hello ${arg}`;
return (
<>
<Child
color="red"
num={123}
fn={hello}
/>
</>
);
};
export default Example;
import "./Child.css";
const Child = ({ color, num, fn }) => { // 分割代入に変更
return (
<div className={`component ${color}`}>
<h3>Hello Component</h3>
<p>{num}</p>
<p>{fn("React")}</p>
</div>
);
};
export default Child;
在中文中叙述上述例子,仅提供一个选项:添加一个布尔属性作为布尔值。如果属性被添加,则值为true;如果未添加属性,则值为false。
import Child from "./components/Child";
const Example = () => {
const hello = (arg) => `Hello ${arg}`;
return (
<>
<Child
color="red"
num={123}
fn={hello}
bool
/>
</>
);
};
export default Example;
import "./Child.css";
const Child = ({ color, num, fn, bool }) => {
return (
<div className={`component ${color}`}>
<h3>Hello Component</h3>
<p>{num}</p>
<p>{fn("React")}</p>
<p>{bool ? "true" : "false"}</p>
</div>
);
};
export default Child;
将对象作为obj属性添加
import Child from "./components/Child";
const Example = () => {
const hello = (arg) => `Hello ${arg}`;
return (
<>
<Child
color="red"
num={123}
fn={hello}
bool
obj={{
name: "Sato",
age: "26",
}}
/>
</>
);
};
export default Example;
import "./Child.css";
const Child = ({ color, num, fn, bool, obj }) => {
return (
<div className={`component ${color}`}>
<h3>Hello Component</h3>
<p>{num}</p>
<p>{fn("React")}</p>
<p>{bool ? "true" : "false"}</p>
<p>{`name:${obj.name} age:${obj.age}`}</p>
</div>
);
};
export default Child;

关于名为”children”的特殊道具
通過在函数组件中添加闭合标签,可以将组件标签中的内容作为children,并在组件内使用该内容作为children处理。
在组件标签内部写入一个名为“测试”的值。
const Example = () => {
return (
<div>
<Container title="Childrenとは?">テスト</Container>
</div>
);
};
export default Example;
在组件标签内的值可以作为childrenprops处理
const Container = ({ title, children }) => { // 分割代入(childrenは固定名詞)
return (
<div className="container">
<h3>{title}</h3>
<p>{children}</p>
</div>
);
};
export default Container;

可以使用组件嵌套等功能
const Example = () => {
return (
<div>
<Container title="Childrenとは?">
<SampleComponent />
</Container>
</div>
);
};
export default Example;
当{children}在组件中执行。
const Container = ({ title, children }) => {
return (
<div className="container">
<h3>{title}</h3>
{children}
</div>
);
};
export default Container;
JSX是什么
使用React对JavaScript语法进行扩展的一种形式。
JSX会转换为JavaScript对象。
“JSX”是”JavaScript XML”的缩写,是一种XML风格的语法用于在React组件中编写标记语言,如下所示。
function render(){
return (
<ul>
<li>togamin.com</li>
<li>fresopiya.com</li>
</ul>
);
}
如果不使用JSX语法,上述代码将变为如下所示。
function render(){
return React.createElement(
'ul',
null,
React.createElement('li', null, 'togamin.com'),
React.createElement('li', null, 'fresopiya.com')
);
}
请参看下述的内容。