我想知道当你传递一个函数时ES6和cloneElement是如何工作的.我需要在父组件的状态中this引用状态,但引用子组件而不是父组件.
下面是常规JavaScript中的代码使它工作,在第一次在ES6中编写它并在键盘上敲我的头后我决定看看它是否是ES6所以我重构并且它工作得很好.
我只是想在ES6中写它,因为其他一切都是,但这让我很难过.
这是我在ES5中的组件:
var Parent = React.createClass({
content: function() {
return React.Children.map(this.props.children, function(child) {
return React.cloneElement(child, {
passThisFunc: this.passThisFunc
})
}.bind(this));
},
passthisfunc: function(component) {
// returns the components props
console.log(this);
// Returns the component so I can do component.props.name
console.log(component);
},
render: function() {
return (
<div>
{ this.content }
</div>
)
}
});
Run Code Online (Sandbox Code Playgroud)
然后在它的孩子们:
var Child = React.createClass({
componentDidMount: function() {
this.props.passThisFunc(this);
}
render: function().....
});
Run Code Online (Sandbox Code Playgroud)
ES6中的组件没有那么不同,它实际上this是记录时引用的内容.
任何重构帮助(特别是父组件)将不胜感激.
编辑 这是我试过的ES6示例:
class Parent extends …Run Code Online (Sandbox Code Playgroud) 我无法弄清楚动态生成具有2种不同大小的多维数组的最佳方法.
我们有一个需要一行4个项目的UI,然后是3.这个模式会重复,直到数组中的内容被用完为止.
这基本上就是我需要做的事情:
// Convert
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
// to
const rows [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10, 11], [12, 13, 14]];
Run Code Online (Sandbox Code Playgroud)
这就是我目前所拥有的,它只是将数组转换为4.
const buildRows = (arr, length) => arr.reduce((rows, val, i) => (
i % length == 0 ? rows.push([val]) : rows[rows.length-1].push(val)
) && rows, []);
Run Code Online (Sandbox Code Playgroud)
提前感谢您的帮助.
我有一个ImageLoader类组件,我试图测试是否正在调用onloada上的函数HTMLImageElement.重要的是要注意ImageLoader按预期工作,我只是无法让测试运行.这是我的类组件的示例:
export default class ImageLoader extends React.Component {
// Omitted for brevity
setSrc = () => {
const { src } = this.props;
if (src) {
this.tmpImg = new Image();
// this.tmpImg.onload is never called
this.tmpImg.onload = () => console.log('???');
this.tmpImg.src = src;
}
}
// Omitted for brevity
}
Run Code Online (Sandbox Code Playgroud)
对于我的测试,我遗漏了我实际测试的内容,因为我从未实际进入过该onload事件(console.log除非我手动调用,否则它不会在测试运行时this.tmpImg.onload()).
import { mount } from 'enzyme';
import ImageLoader from '../ImageLoader';
describe('ImageLoader', () => {
it('renders', …Run Code Online (Sandbox Code Playgroud)