[fix] default DOM element for 'View' (part 2)

First patch: 41159bcb10

@chriskjaer mentioned that changing from 'div' to 'span' introduces
different validation errors, e.g., <span><form>a</form></span>.

This patch uses 'context' to switch to a 'span' element if a 'View' is
being rendered within a 'button' element.
This commit is contained in:
Nicolas Gallagher
2016-07-12 11:03:31 -07:00
parent 5f3f4db7a6
commit 17b30aceb2
2 changed files with 26 additions and 4 deletions

View File

@@ -7,8 +7,20 @@ import View from '../'
import { mount, shallow } from 'enzyme'
suite('components/View', () => {
suite('rendered element', () => {
test('is a "div" by default', () => {
const view = shallow(<View />)
assert.equal(view.is('div'), true)
})
test('is a "span" when inside <View accessibilityRole="button" />', () => {
const view = mount(<View accessibilityRole='button'><View /></View>)
assert.equal(view.find('span').length, 1)
})
})
test('prop "children"', () => {
const children = 'children'
const children = <View testID='1' />
const view = shallow(<View>{children}</View>)
assert.equal(view.prop('children'), children)
})

View File

@@ -50,9 +50,18 @@ class View extends Component {
style: {}
};
constructor(props, context) {
super(props, context)
this._normalizeEventForHandler = this._normalizeEventForHandler.bind(this)
static childContextTypes = {
isInAButtonView: PropTypes.bool
};
static contextTypes = {
isInAButtonView: PropTypes.bool
};
getChildContext() {
return {
isInAButtonView: this.props.accessibilityRole === 'button'
}
}
render() {
@@ -72,6 +81,7 @@ class View extends Component {
const props = {
...other,
component: this.context.isInAButtonView ? 'span' : 'div',
onClick: this._normalizeEventForHandler(this.props.onClick),
onClickCapture: this._normalizeEventForHandler(this.props.onClickCapture),
onTouchCancel: this._normalizeEventForHandler(this.props.onTouchCancel),