问题
In my JSX, I have a case of a conditional rendering logic - when element A renders something (it's render()
function returns something other than null
), then also render element B, just above the element A.
Code example (simplified) would look like this:
function render() {
let elemA = (<ElementA someProp={this.someVar} />);
if (elemA.isNull()) {
return (
<div>
{ ...someElements }
</div>
);
}
return (
<div>
{ ...someElements }
<ElementB />
{ elemA }
</div>
);
}
So my question is - Is there any way to have the elemA.isNull()
check?
回答1:
No, there's no way to determine what a child will render using React. The standard way to do this is to expose some utility function that says whether A will render.
Something like:
if (AUtils.isStoryValid(story)) {
return <A story={story} />;
} else {
return <B story={story} />;
}
回答2:
You can use the following higher order component (HOC) to intercept the render method of ElementA and accomplish what you want:
function withNullCheck(WrappedComponent) {
return class NullChecker extends WrappedComponent {
render() {
const result = super.render();
return(
<div>
{ this.props.alwaysPrefix }
{ result && this.props.ifNotNullPrefix }
{ result ? result : this.props.ifNull }
{ result && this.props.ifNotNullAppend }
{ this.props.alwaysAppend }
</div>
);
}
}
}
You would use it like this:
const NullCheckedElementA = withNullCheck(ElementA);
...
function render() {
return (
<NullCheckedElementA
alwaysPrefix={someElements}
ifNotNullPrefix={elemB}
someProp={this.someVar}
/>
);
}
回答3:
So I ran into a situation where I was stuck having to do this, here is a way that works (though the hackiness might make you cry).
Should only be used as a last resort because it really is a total hack and you'll take a ~0-20ms performance hit depending on component complexity. (Provider is there assuming you're using redux and your component depends on your redux state):
import { renderToStaticMarkup } from 'react-dom/server';
import { Provider } from 'react-redux';
import store from 'pathToYourReduxStoreInstance';
export default function isRenderingNull(componentInstance) {
return !renderToStaticMarkup(
<Provider store={store}>
{componentInstance}
</Provider>
)
}
来源:https://stackoverflow.com/questions/33136399/is-there-a-way-to-tell-if-reactelement-renders-null