gpt4 book ai didi

javascript - 如何在此 React 组件中修复“对象的 "Cannot assign to read only property ' 样式”?

转载 作者:数据小太阳 更新时间:2023-10-29 05:14:20 25 4
gpt4 key购买 nike

我正在创建自己的自定义选项卡组件。它由一个选项卡标题组成,每个选项卡标题都有一个正文部分。单击选项卡标题时,应将相应主体的样式设置为 display:block,将所有其他样式设置为 display:none

由于某些原因,我收到此错误:

Cannot assign to read only property 'style' of object

我知道我不能手动更改样式属性,因为它似乎是只读的,但我该如何解决/解决这个问题?

这是我的代码:

Tabs.js

import React, { Component } from 'react';

class Tabs extends Component {

constructor() {
super();
this.state = {
activeIndex: 0,
};
this.tabHeads = [];
}

// Initial composition of tab heads
componentWillMount() {
React.Children.map(this.props.children, (el, i) => {
const tab = el;
const key = `tabKey${i}`;
this.tabHeads.push((
<div role="button" onClick={e => this.onTabClick(e, i)} key={key}>{tab.props.title}</div>
));
});
}

// Called when user clicks a tab head
onTabClick(e, i) {
this.setState({ activeIndex: i });
}

render() {
// Set display none or block for each tab
React.Children.map(this.props.children, (el, i) => {
const tab = el;
let visibility = 'none';
if (i === this.state.activeIndex) visibility = 'block';
const newStyle = Object.assign({}, tab.props.style, { display: visibility });
tab.props.style = newStyle;
});

return (
<div style={this.props.style}>
{this.tabHeads}
{this.props.children}
</div>
);
}
}

export default Tabs;

用法是这样的:

render() {
const tabStyles = [
{ padding: '20px' }, // Tab 0
{ padding: '20px' }, // Tab 1
];

<Tabs>

<Tab style={tabStyles[0]} title="Tab1">
<div>Content 1</div>
</Tab>

<Tab style={tabStyles[1]} title="Tab2">
<div>Content 2</div>
</Tab>

</Tabs>
}

最佳答案

您尝试更改此行中的属性值:
tab.props.style = newStyle;
但是 React 中的 props 是只读的,你不能手动更改它们的值。请查看 React docs了解更多详情。
要修复它,您可以使用 React.cloneElement它允许克隆具有将合并到现有属性中的新属性的元素:

render() {
let childrenWithNewProps = React.Children.map(this.props.children, (el, i) => {
let visibility = 'none';
if (i === this.state.activeIndex) visibility = 'block';
return React.cloneElement(el, {
style: {
display: visibility
}
}
)
});

return (
<div style={this.props.style}>
{this.tabHeads}
{childrenWithNewProps}
</div>
);
}

关于javascript - 如何在此 React 组件中修复“对象的 "Cannot assign to read only property ' 样式”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44186498/

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