组件组合(Vue中的插槽)
vue中:
- 使用slot技术,也就是通过组件标签体内传入结构
React中:
- 使用children props:通过组件标签体传入结构
- 使用render props:通过标签属性传入结构,一般用render函数结构
1、children props
children props 在函数式组件中使用
function DetailTitle(props){return <div>{props.children[0]}新闻标题</div>}function Detail(props){return (<div><DetailTitle><span>我是</span><span>欢迎!</span></DetailTitle><p>新闻内容</p></div>)}
2、render props
render props 在类式组件中使用
class Parent extends Component {render(){return <><div>我是Parent组件</div><A render={(name) => { return <B name={ name } /> }} /></>}}class A extends Component {state = { name:'fang' }render(){return <><div>我是A组件</div>{ this.props.render(this.state.name) }</>}}class B extends Component {render(){return <div>我是B组件{ this.props.name }</div>}}
3、具名插槽
function DetailTitle(props){return <div>{props.leftSlot}新闻标题</div>}function Detail(props){return (<div><DetailTitleleftSlot={ <span>我是</span> }rightSlot={ <span>欢迎!</span>}/><p>新闻内容</p></div>)}
4、路由导航守卫
function CheckLogin(props) {const isLogin = localStorage.getItem("token") ? true : false;return (<Routerender={() => {return isLogin ? props.children : <Redirect to="/login" />;}}></Route>);}
表单
记录表单的使用细节
import { useRef } from 'react'import Card from './Card'function MeetupItem(props) {// 浏览器表单提交的默认行为会发送一个请求,到提供此页面的服务器// 捕获表单提交,并执行自定义的业务逻辑// 当表单提交的时候,会对应触发submitHandlerconst titleInputRef = useRef()function submitHandler(event) {// 我们不想浏览器触发默认事件,而是需要运行我们自己的逻辑event.preventDefault()// 获取输入框输入的值const enteredTitle = titleInputRef.current.valueconsole.log(enteredTitle)}return (<><Card>{/* 我们可以在表单上面添加submit,默认情况下会触发提交事件 */}<form onSubmit={submitHandler}><div>{/* htmlFor 将标签label与输入框input关联在一起 */}<label htmlFor='title'>Meetup Title</label><hr /><input type='text' required id="title" ref={titleInputRef}></input></div><div>{/* htmlFor 将标签label与输入框input关联在一起 */}<label htmlFor='description'>Description</label><hr /><textarea id="description" required rows="6"></textarea></div><hr /><button>Submit</button></form></Card></>)}export default MeetupItem
上下文 context
Context 提供了一个无需为每层组件手动添加 props,就能在组件树间进行数据传递的方法。
Context 提供了一种在组件之间共享此类值的方式,而不必显式地通过组件树的逐层传递 props。
Context 设计目的是为了共享那些对于一个组件树而言是“全局”的数据,例如当前认证的用户、主题或首选语言。 Context 主要应用场景在于很多不同层级的组件需要访问同样一些的数据。请谨慎使用,因为这会使得组件的复用性变差。 如果你只是想避免层层传递一些属性,组件组合(component composition)有时候是一个比 context 更好的解决方案。
import { createContext, useState } from "react"// context是一个JS对象,可以将其存储到一个常量中// 这个对象是由context所创建, 会包含react component// 参数为上下文的初始值(也就是组件范围的状态),可以是对象的形式const FavoritesContext = createContext({favorites: [],totalFavorites: 0, // 收藏夹总数addFavorite: (favoriteMeetup) => {},removeFavorite: (meetupId) => {},itemIsFavorite: (meetupId) => {}})// 此外,我们还需要有能够添加/删除收藏夹的这些值// 为此,我们需要一个组件FavoritesContextProvider// 而这个功能组件会给上下文提供必要的组件(会与上下文产生交互的组件)或是负责更新上下文的值// 之后在index.js中使用并包装它export function FavoritesContextProvider(props) {// 在这里我们可以用状态来管理上下文中的值// 当我们修改状态时候,这里的这个组件会在执行,这个组件的更新会引起其包裹的所有关联的更新// 也即如果我们改变在这个组件中上下文的值的时候,所有正在监听这个上下文的组件将会被更新const [userFavorites, setUserFavorites] = useState([])// 修改状态值的回调// 我们不仅仅想让状态可以让不同组件访问,也需要不同组件能够访问操作改变状态值的函数// 于是我们需要向外暴露这些函数的指向,并将指向添加到context中,传递给不同的组件// 添加收藏function addFavoriteHandler(favoriteMeetup) {// concat合并添加进来的收藏// 下面这行会有个问题,在于useState并非是立即状态更新的// 所以如果我们依赖于最后的状态快照,我们需要换一个写法// setUserFavorites(userFavorites.concat(favoriteMeetup))// 这种写法能保证我们此处的状态更新setUserFavorites((prevUserFavorites)=>{return prevUserFavorites.concat(favoriteMeetup)})}// 移除收藏function removeFavoriteHandler(meetupId) {setUserFavorites((prevUserFavorites)=>{// filter会过滤掉返回false的项return prevUserFavorites.filter(meetup => meetup.id !== meetupId)})}// 判断是否为收藏夹function itemIsFavoriteHandler() {// some只要其中一项为true便为truereturn userFavorites.some(meetup => meetup.id === meetupId)}// 存储上下文const context = {favorites: userFavorites,totalFavorites: userFavorites.length,addFavorite: addFavoriteHandler,removeFavorite: removeFavoriteHandler,itemIsFavorite: itemIsFavoriteHandler}return (<FavoritesContext.Provider value={context}>{props.children}</FavoritesContext.Provider>)}export default FavoritesContext
import { useContext } from 'react'import FavoritesContext from '../store/favorites-context'import MeetupList from './MeetupList'function FavoritesPage() {const favoriteCtx = useContext(FavoritesContext)// 这里需要一个content来应对收藏夹里没哟收藏的东西的情况let contentif(favoriteCtx.totalFavorites === 0) {content = <p>You got no favorites yet. Go head! Add some?</p>}else {content = <MeetupList meetup={favoriteCtx.favorites}></MeetupList>}return (<section><h1>My Favorites</h1>{content}</section>)}export default FavoritesPage
