这是我计算图像高度和宽度的函数,但我不得不使用反应原生图像。 getSize but this has a callback which a has a delay somehow and the return brock seems to execute before this image. getSize
完成。
renderNode (node, index, siblings, parent, defaultRenderer) {
let finalwidth ;
let finalheight;
if (node.name === 'img') {
const a = node.attribs;
Image.getSize(a.src, (width, height) => {
let screenSize = Dimensions.get('window');
let hRatio = screenSize.width / width;
let vRatio = screenSize.height / height;
let ratio = Math.max(hRatio, vRatio);
let rat = hRatio / vRatio;
finalwidth = parseInt(width * ratio);
finalheight = parseInt(height * ratio);
alert(finalwidth + 'x' + finalheight) // they have values here
})
return (
<Image
key={index}
source={{uri: a.src}}
resizeMode={'stretch'}
style={{
width: finalwidth, //finalwidth is null here
height:finalheight, //finalheight is null here
}}
/>
);
}
}
实际上,我想在我的返回brock中访问最终宽度和最终高度的值
答案 0 :(得分:1)
使用setState()并将这些值设置为state,以便在更新数据时重新呈现组件
constructor(props){
super(props);
this.state={finalwidth : null,
finalheight: null
}
}
renderNode (node, index, siblings, parent, defaultRenderer) {
if (node.name === 'img') {
const a = node.attribs;
Image.getSize(a.src, (width, height) => {
let screenSize = Dimensions.get('window');
let hRatio = screenSize.width / width;
let vRatio = screenSize.height / height;
let ratio = Math.max(hRatio, vRatio);
let rat = hRatio / vRatio;
finalwidth = parseInt(width * ratio);
finalheight = parseInt(height * ratio);
this.setState({finalwidth, finalheight})
alert(finalwidth + 'x' + finalheight) // they have values here
})
return (
<Image
key={index}
source={{uri: a.src}}
resizeMode={'stretch'}
style={{
width: this.state.finalwidth, //finalwidth from state
height: this.state.finalheight, //finalheight from state
}}
/>
);
}
}