[fix] disallow text node children of View

Fix #627
This commit is contained in:
Nicolas Gallagher
2017-09-14 14:59:37 -07:00
parent 32a23136af
commit 0ad6ab948b
2 changed files with 20 additions and 4 deletions
+12 -4
View File
@@ -12,10 +12,18 @@ describe('components/View', () => {
}); });
}); });
test('prop "children"', () => { describe('prop "children"', () => {
const children = <View testID="1" />; test('text node throws error', () => {
const component = shallow(<View>{children}</View>); const children = 'hello';
expect(component.contains(children)).toEqual(true); const render = () => shallow(<View>{children}</View>);
expect(render).toThrow();
});
test('non-text is rendered', () => {
const children = <View testID="1" />;
const component = shallow(<View>{children}</View>);
expect(component.contains(children)).toEqual(true);
});
}); });
describe('prop "hitSlop"', () => { describe('prop "hitSlop"', () => {
+8
View File
@@ -11,6 +11,7 @@ import applyLayout from '../../modules/applyLayout';
import applyNativeMethods from '../../modules/applyNativeMethods'; import applyNativeMethods from '../../modules/applyNativeMethods';
import { bool } from 'prop-types'; import { bool } from 'prop-types';
import createElement from '../../modules/createElement'; import createElement from '../../modules/createElement';
import invariant from 'fbjs/lib/invariant';
import StyleSheet from '../../apis/StyleSheet'; import StyleSheet from '../../apis/StyleSheet';
import ViewPropTypes from './ViewPropTypes'; import ViewPropTypes from './ViewPropTypes';
import React, { Component } from 'react'; import React, { Component } from 'react';
@@ -49,6 +50,13 @@ class View extends Component {
...otherProps ...otherProps
} = this.props; } = this.props;
if (process.env.NODE_ENV !== 'production') {
invariant(
typeof this.props.children !== 'string',
'A text node cannot be a child of a <View>'
);
}
const { isInAParentText } = this.context; const { isInAParentText } = this.context;
otherProps.style = [styles.initial, isInAParentText && styles.inline, style]; otherProps.style = [styles.initial, isInAParentText && styles.inline, style];