0
点赞
收藏
分享

微信扫一扫

13个React代码片段汇总

小云晓云 2022-11-09 阅读 194

13个React代码片段汇总_javascript

英文 | https://medium.com/frontend-canteen/a-summary-of-react-by-10-code-snippets-15aca7c5a8c8


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]} />)

总结

以上就是我今天分享的13个关于React的代码片段,希望这个对你有帮助。

感谢您的阅读,祝编程愉快!



13个React代码片段汇总_html_02



13个React代码片段汇总_html_03


举报

相关推荐

0 条评论