13个React代码片段汇总
01、Create React App
$ create-react-app YOUR_APP_NAME
Create React App 是一个用于创建 React 项目的 CLI。
02、JSX
const element = <h1>Hello, world!</h1>;
我们可以通过 JSX 在 JavaScript 中编写 HTML。
03、在 JSX 中嵌入表达式
const name = 'Josh Perez';
const element = <h1>Hello, {name}</h1>;
只需使用 {} 来包装 JavaScript 表达式。
04、创建一个组件
import React from 'react'
const Hello = () => <div>Hello World</div>
export default Hello
它是一个简单的、无状态的、功能性的组件。
05、创建类组件
import React from 'react'
class Hello extends React.Component {
render() {
return <div>Hello World</div>
}
}
export default Hello
06、将值传递给组件
const User = ({name, email}) => {
<div>
<div> name: {name} </div>
<div> email: {email} </div>
</div>
}
export default User
用法:
<User name="Jon" age="35">
07、组件嵌套
const Child = (props) => (
<div>{props.message}</div>
)
const Father = () => (
return (<div>
<div> I am father</div>
<Child message="aaa"></Child>
</div>)
)
08、向组件添加状态
import { useState } from "react";
export default function Counter(){
// Declare a new state variable, which we'll call "count"
let [count, setCount] = useState(0)
return <div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}> add</button>
</div>
}
09、声明多个状态变量
当然,我们可以使用 useStates 定义多个状态。
function ManyStates() {
// Declare multiple state variables!
const [name, setName] = useState('');
const [age, setAge] = useState(0);
const [todos, setTodos] = useState([{ text: 'Eat' }]);
// ...
}
10、使用效果
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
11、处理事件
function Form() {
function handleSubmit(e) {
e.preventDefault();
console.log('You clicked submit.');
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}
12、条件渲染
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <UserGreeting />;
}
return <GuestGreeting />;
}
用法:
<Greeting isLoggedIn={false} />
13、列表组件
function NumberList(props) {
const numbers = props.numbers;
const listItems = numbers.map((number) =>
<li>{number}</li>
);
return (
<ul>{listItems}</ul>
);
}
用法:
<NumberList numbers={[1, 2, 3, 4, 5]} />)