Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React.forwarRef #180

Open
yaofly2012 opened this issue Sep 28, 2020 · 0 comments
Open

React.forwarRef #180

yaofly2012 opened this issue Sep 28, 2020 · 0 comments
Labels

Comments

@yaofly2012
Copy link
Owner

yaofly2012 commented Sep 28, 2020

React.forwardRef

一、语法

1.1 实参:是个渲染函数(render function)

(props, ref) => ReactElement
  1. 可以增加displayName属性,方便调试;
  2. 不可以含有defaultProps, propTypes属性。
function RenderFunc(props, ref) {
	return  (
		<button ref={ref} className="FancyButton">
		  {props.children}
		</button>
	)
}

RenderFunc.defaultProps = {
	className: 'FancyButton'
}

const FancyButton = React.forwardRef(RenderFunc);

React就会warning了:

Warning: forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?

并且此时FancyButton.defaultPropsundefined。正确的用法是:

function RenderFunc(props, ref) {
	return  (
		<button ref={ref} className={props.className}>
		  {props.children}
		</button>
	)
}

const FancyButton = React.forwardRef(RenderFunc);

FancyButton.defaultProps = {
	className: 'FancyButton'
}

1.2 返回值:React组件

返回值才是React组件,此时可以才可以添加defaultPropspropTypes

1.3 forwardRef render functions do not support propTypes or defaultProps

  1. render function并不是React组件,其返回值才是React组件。
    render function只是转发ref的函数,有两个形参(props, ref),React组件函数只有一个形参(props)。

  2. defaultProps, propTypes专属于React组件的,防止误用React做了校验

二、多子组件的ref?

参考

  1. Reactjs: Forwarding Refs
  2. Stateless Component: React.forwardRef make defaultProps invalid
@yaofly2012 yaofly2012 changed the title React.forwarRef ? React.forwarRef Sep 29, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant