我想做的事
我试图通过设置nativeProps来创建一个Animated.View元素数组。我出于速度原因选择这样做。
问题
虽然在render方法中直接放置具有nativeProp refs的组件不会产生任何问题,但如果refs在数组中,则无法识别它们。
示例
componentWillMount: function() {
this.arrayOfElements = [];
this.exampleView1.nativeProps = (null : ?{ setNativeProps(props: Object): void });
this.exampleView2.nativeProps = (null : ?{ setNativeProps(props: Object): void });
var key1 = "Example View 1"
var key2 = "Example View 2"
this.arrayOfElements.push(
<Animated.View key={key1} ref={(nativeProps) => { this.exampleView1.nativeProps = nativeProps }} >
<Shape />
</Animated.View>
);
this.arrayOfElements.push(
<Animated.View key={key2} ref={(nativeProps) => { this.exampleView2.nativeProps = nativeProps }} >
<Shape />
</Animated.View>
);
},
componentDidMount: function() {
console.log(this.exampleView1.nativeProps); // null --> Means the component was *not* mounted
console.log(this.exampleView2.nativeProps); // void function --> Means the component was mounted
},
render: function() {
<View>
{this.arrayOfElements}
</View>
},
我没有足够的经验在JSX中理解为什么会这样,但重要的是我创建了一个带有refs的JSX循环,允许我设置nativeProps。任何帮助都将非常感激!
答案 0 :(得分:0)
我仍然不知道为什么会出现原始问题,但可以使用map方法正确加载refs。举个例子:
render: function() {
var arrayOfRefs = ['exampleView1', 'exampleView2'];
return(
<View>
{this.arrayOfRefs.map((name, index) => (
<Animated.View key={name} ref={(nativeProps) => { this[name].nativeProps = nativeProps }} >
<Shape />
</Animated.View>
))}
</View>
);
},