我有以下React组件:
import React, {Component} from 'react';
import $ from 'jquery';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
class SamplesInnerLrg extends Component {
playSample (refName,event) {
var idClicked = this.refs[refName];
var linkAudio = $(idClicked).children("#myAudio")[0];
linkAudio.play();
}
render() {
return this.props.samples.map((sample) => {
return (
<div key={sample.id} className="sample-comp-lge">
<div className="sample-comp-lge-header">
<span className="sample-comp-lge-Name">{sample.sampleName}</span>
<span className="sample-comp-lge-id">{sample.sampleFamily}</span>
</div>
<div className="sample-comp-lge-audio" ref={sample.id} onClick={this.playSample.bind(this,sample.id)}>
<audio preload="auto" id="myAudio">
<source src={sample.soundSource} type="audio/wav" />
</audio>
</div>
<div className="sample-comp-lge-owner">{sample.uploader}</div>
</div>
)
})
}
}
function mapStateToProps(state) {
return {
samples:state.samples
};
}
export default connect(mapStateToProps)(SamplesInnerLrg);
这里的问题是我得到错误&#34;必须返回有效的React元素(或null)&#34;。在看了几个类似的问题后,看起来通常的问题是没有将JSX包装在父非并行元素中。在我的上面的代码中它被父包裹,所以不知道为什么我得到错误。
值得一提的是错误说有问题的组件是不变违规:SamplesInnerLrg.render()
React的新手,所以感谢我能得到的所有帮助
答案 0 :(得分:4)
React应返回单个HTML节点。在您的情况下,您将返回一组节点。
试试这个:
return <div>
{
this.props.samples.map((sample) => {
return (
<div key={sample.id} className="sample-comp-lge">
<div className="sample-comp-lge-header">
<span className="sample-comp-lge-Name">{sample.sampleName}</span>
<span className="sample-comp-lge-id">{sample.sampleFamily}</span>
</div>
<div className="sample-comp-lge-audio" ref={sample.id} onClick={this.playSample.bind(this,sample.id)}>
<audio preload="auto" id="myAudio">
<source src={sample.soundSource} type="audio/wav" />
</audio>
</div>
<div className="sample-comp-lge-owner">{sample.uploader}</div>
</div>
)
})
}
</div>
通过执行此操作,您将在<div>
节点下包装节点数组。