React点击按钮功能正常却打开白标错误页如何解决
问题场景
我定义了如下TypeScript接口与React类组件:
export interface DocRow { docName: string; docDate: string; docUrl: string; packId: string; } interface Props { dRow: DocRow[]; policy: string; } interface State { disableIssueButton: boolean; showIssueCertPrompt: boolean; } export class IssueButton extends React.Component<Props, State> { loggingService: LoggingService; issueCertService: IssueCertService; constructor(props: Props) { super(props); this.loggingService = new LoggingService(); this.issueCertService = new IssueCertService(); this.state = { disableIssueButton: false, showIssueCertPrompt: false }; } showIssue = () => { this.setState({ showIssueCertPrompt: true }); } hideIssue = () => { this.setState({ showIssueCertPrompt: false }); } disableIssueButton = () => { this.setState({ disableIssueButton: true }); } render() { // const { policy } = this.props; return this.props.dRow.map(dRow => { if (dRow.docName === 'Cert') { return ( <React.Fragment> <Button onClick={this.showIssue} primary={true} fullWidth={false} disabled={this.state.disableIssueButton} > Issue cert </Button> <IssueCert handleClose={this.hideIssue} disableIssueButton={this.disableIssueButton} showIssueCertPrompt={this.state.showIssueCertPrompt} policy={this.props.policy} packId={dRow.packId} /> </React.Fragment> ); } else { return; } }); } }
点击Issue cert按钮时,绑定的预期业务功能可正常执行,但浏览器会同时新开标签页访问DocRow.docUrl对应的地址,页面空白且无限加载,显示白标错误页。已为按钮绑定了自定义点击处理逻辑,仍出现该异常,需要找到原因并阻止这种非预期的页面跳转行为。
问题原因
出现该异常有两个核心诱因:
- 按钮所在的文档行外层,被父组件包裹了指向
dRow.docUrl的<a>标签。点击按钮时,点击事件会沿着DOM树向上冒泡,最终触发外层<a>标签的默认跳转逻辑,绑定在按钮上的onClick只执行了弹窗展示逻辑,没有拦截事件冒泡和默认行为,因此跳转和业务逻辑会同时触发。 - 自定义
Button组件底层渲染原生<button>元素时,若未显式设置type="button",在表单环境下默认type为submit,会触发表单默认提交跳转,也可能加剧异常。
另外当前render方法遍历数组时,非Cert项直接return;会返回undefined,React渲染数组节点时会抛出不必要的警告,属于附带的代码不规范问题。
修复方案
按以下步骤修改代码即可解决问题:
- 修改
showIssue点击处理函数,接收事件对象,主动阻止默认行为和事件冒泡:showIssue = (e: React.MouseEvent<HTMLButtonElement>) => { e.preventDefault(); e.stopPropagation(); this.setState({ showIssueCertPrompt: true }); } - 给Button组件显式传入
type="button"属性,避免原生按钮默认submit行为触发意外提交:<Button type="button" onClick={this.showIssue} primary={true} fullWidth={false} disabled={this.state.disableIssueButton} > Issue cert </Button> - 修复render方法的返回值规范问题,将else分支的
return;修改为return null;,避免React渲染数组时的空节点警告。
内容的提问来源于stack exchange,提问作者runnerpaul
相关产品推荐
相关产品推荐

