我看到 React.forwardRef 似乎是将 ref 传递给子功能组件的认可方式,来自 react 文档:
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
Run Code Online (Sandbox Code Playgroud)
但是,与简单地传递自定义道具相比,这样做有什么优势?:
const FancyButton = ({ innerRef }) => (
<button ref={innerRef} className="FancyButton">
{props.children}
</button>
));
const ref = React.createRef();
<FancyButton innerRef={ref}>Click me!</FancyButton>;
Run Code Online (Sandbox Code Playgroud)
我能想到的唯一优势可能是为 refs 提供了一致的 api,但还有其他优势吗?传递自定义道具是否会影响渲染时的差异并导致额外的渲染,肯定不会因为 ref 在current字段中存储为可变状态?
例如,假设您想传递多个 refs(这可能表明代码异味,但仍然如此),那么我能看到的唯一解决方案是使用 customRef 道具。
我想我的问题是使用forwardRef自定义道具的价值是什么?
我正在尝试使用 GL_POINTS 在片段着色器中使用法线贴图绘制一个简单的球体。目前,我只是在屏幕上绘制一个点并应用片段着色器将其“球化”。
但是,我在正确为球体着色时遇到了麻烦(或者至少我认为是)。看来我正确地计算了 z,但是当我将“正常”颜色应用于gl_FragColor它时,它看起来不太正确(或者这是人们对法线贴图的期望?)。我假设 gl_PointCoord 和片段坐标之间存在一些不一致,但我不太明白。
顶点着色器
precision mediump float;
attribute vec3 position;
void main() {
gl_PointSize = 500.0;
gl_Position = vec4(position.xyz, 1.0);
}
Run Code Online (Sandbox Code Playgroud)
片段着色器
precision mediump float;
void main() {
float x = gl_PointCoord.x * 2.0 - 1.0;
float y = gl_PointCoord.y * 2.0 - 1.0;
float z = sqrt(1.0 - (pow(x, 2.0) + pow(y, 2.0)));
vec3 position = vec3(x, y, z);
float mag = dot(position.xy, position.xy);
if(mag > 1.0) discard;
vec3 normal = normalize(position);
gl_FragColor …Run Code Online (Sandbox Code Playgroud)