我有一个React组件,如下所示。当我执行以下组件的测试用例时,尽管在浏览器上我看到生成了元素,但编译时没有错误,但出现了以下错误。
错误:
TypeError:无法读取null的属性“ focus”
at Check.componentDidMount (src/components/Payments/Check.js:42:42)
at node_modules/react-test-renderer/lib/ReactCompositeComponent.js:262:25
at measureLifeCyclePerf (node_modules/react-test-renderer/lib/ReactCompositeComponent.js:73:12)
at node_modules/react-test-renderer/lib/ReactCompositeComponent.js:261:11
at CallbackQueue.notifyAll (node_modules/react-test-renderer/lib/CallbackQueue.js:74:22)
at ReactTestReconcileTransaction.close (node_modules/react-test-renderer/lib/ReactTestReconcileTransaction.js:34:26)
at ReactTestReconcileTransaction.closeAll (node_modules/react-test-renderer/lib/Transaction.js:207:25)
at ReactTestReconcileTransaction.perform (node_modules/react-test-renderer/lib/Transaction.js:154:16)
at batchedMountComponentIntoNode (node_modules/react-test-renderer/lib/ReactTestMount.js:67:27)
at ReactDefaultBatchingStrategyTransaction.perform (node_modules/react-test-renderer/lib/Transaction.js:141:20)
at Object.batchedUpdates (node_modules/react-test-renderer/lib/ReactDefaultBatchingStrategy.js:60:26)
Check.js
export default class Check extends Component {
static displayName = 'Check';
static propTypes = {
check: PropTypes.object,
translate: PropTypes.func.isRequired,
countries: PropTypes.object,
states: PropTypes.object,
setCheckState: PropTypes.func.isRequired
};
onChange = (fieldName, newValue) => {
let sanitizedFieldName = fieldName.replace('selected', '');
sanitizedFieldName = sanitizedFieldName.charAt(0).toLowerCase() + sanitizedFieldName.substr(1);
const newCheckState = {
...this.props.check,
[sanitizedFieldName]: newValue
};
this.props.setCheckState(newCheckState, sanitizedFieldName === 'country');
}
componentDidMount() {
document.getElementById('mainHeader').focus();
}
render() {
const { translate, check, countries, states } = this.props;
const parentType = 'check';
const stateObj = states[check.country] || { optionArray: [] };
return (
<div>
<div tabIndex="0" id="mainHeader"><h1 {...resolve(CheckStyles, 'mainHeader')}>
{translate('PanelPaymentsCheckHeaderText')}
</h1></div>
<div {...resolve(CheckStyles, 'bankInfoContainer')}>
<h3 {...resolve(CheckStyles, 'bankAccountHeader')}>
{translate('PanelPaymentsCheckSubHeaderText')}
</h3>
........
........
</div>
</div>
);
}
}
答案 0 :(得分:1)
尝试使用ref
代替id
,即
componentDidMount() {
this.refs.mainHeader.focus();
}
...
<div tabIndex="0" ref="mainHeader"><h1 {...resolve(CheckStyles, 'mainHeader')}>
答案 1 :(得分:0)
我添加了null检查以消除错误。真是愚蠢的解决方法。
componentDidMount() {
if(this.refs.mainHeader){
this.refs.mainHeader.focus();
}
}