【发布时间】:2020-04-12 23:29:58
【问题描述】:
我需要将数组数组传递给 React 16.12 中的子组件。我不希望将数组分解为父级中的元素(仍然是数组)并将其作为一个整体传递。但似乎 React 将内部数组转换为字符串。 我使用以下场景来解释这个案例,这不是我的应用所做的,就是这样:
这是我想要传递给孩子的数组 -> [[0, 0], [100, 0], [100, 100], [0, 100]]
这是我记录子道具时浏览器(firefox、chrome)返回的内容 -> [[0, 0], [100, 0], [100, 100], [0, 100]]
似乎一切都很好......
- 这是我想在屏幕上显示道具内容时的代码和渲染结果 ->
class Rectest extends React.Component {
constructor(props) {
super(props);
}
render() {
console.log(this.props)
return (
<div>
<h6>
{this.props.corners[0]}
</h6>
<h6>
{this.props.corners[1]}
</h6>
<h6>
{this.props.corners[2]}
</h6>
<h6>
{this.props.corners[3]}
</h6>
</div>
)
}
}
道具日志-> [[0, 127 ], [128, 0 ], [4, 133 ], [4, 127 ]]
h6标签中渲染的内容-> 0127 1280 4133 4127
看起来内部数组在渲染函数中被视为字符串...
- 当我使用这段代码时 ->
class Rectest extends React.Component {
constructor(props) {
super(props);
}
render() {
console.log(this.props)
return (
<div>
<h6>
{this.props.corners[0][0]}
</h6>
<h6>
{this.props.corners[1]}
</h6>
<h6>
{this.props.corners[2]}
</h6>
<h6>
{this.props.corners[3]}
</h6>
</div>
)
}
}
我收到一个类型错误:TypeError: this.props.corners[0] is undefined
最后,这是父组件中的子组件:
<Rectest corners={this.state.photoCorners}/>
而 this.props.corners[0] 似乎是一个数组,因为这段代码:
console.log(Array.isArray(this.props.corners[0]))
返回真。
【问题讨论】:
-
好的,但是为什么要在h6标签内显示数组元素呢?
-
@Baran Nazari 你想做什么?有什么要求
-
我不想给他们看!我想把案子说清楚。 @Ramesh
-
我想根据道具画一个矩形。 @Vahid Akhtar
-
但是可能的解决方案对我来说比这种情况有用得多。正如我所提到的,有一些方法可以打破数组并单独发送内部部分。我只是做了这个简单的场景来说明这一点,我希望它不会造成更多的混乱:)
标签: reactjs state react-props