gpt4 book ai didi

javascript - 类型错误 : Cannot read property 'focus' of null

转载 作者:行者123 更新时间:2023-12-04 13:20:14 25 4
gpt4 key购买 nike

我有一个如下的 React 组件。当我为以下组件执行测试用例时,尽管在浏览器上我看到生成了元素并且编译中没有错误,但我得到了以下错误。

错误 :

TypeError:无法读取 null 的属性“焦点”

  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)

检查.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>
);
}
}

最佳答案

我添加了空检查以消除错误。这是一个愚蠢的解决方案。

componentDidMount() {
if(this.refs.mainHeader){
this.refs.mainHeader.focus();
}
}

关于javascript - 类型错误 : Cannot read property 'focus' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53901553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com