Javascript React Native-按键更改组件样式
我知道在Javascript React Native-按键更改组件样式,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我知道在html和javascript中,可以通过id和class更改自己的css样式,在react native中,如何设置/更改组件样式。我有map一个组件列表,每个组件都设置了一个键值。当我调用一个函数时,我想更改一个组件样式 例如:更改键为2组件样式 _RenderSpecialItem(){ return this.state.speciallist.map((item, i)=>{ return( <SpecialItem key
html
和javascript
中,可以通过id
和class
更改自己的css
样式,在react native中,如何设置/更改组件样式。我有map
一个组件列表,每个组件都设置了一个键
值。当我调用一个函数时,我想更改一个组件样式
例如:更改键
为2组件样式
_RenderSpecialItem(){
return this.state.speciallist.map((item, i)=>{
return(
<SpecialItem
key={i}
/>
);
});
}
_ChangeStyle(){
//do something
}
\u RenderSpecialItem(){
返回this.state.specialist.map((项,i)=>{
返回(
);
});
}
_ChangeStyle(){
//做点什么
}
您可以使用,但这不是一个好的做法,有关更多信息,请阅读
直接操纵将不是你经常使用的工具;通常,您只能将其用于创建连续动画,以避免渲染组件的开销
在链接中。否则,应在“组件”中设置状态并更改状态以更新样式
e、 g
首先设置组件的参考:
<SpecialItem
key={i}
ref={(thisItem) => this[`item-${i}`] = thisItem}
/>
完整示例
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
speciallist: ['aaa', 'bbb', 'ccc']
}
}
componentDidMount() {
this['text-0'].setNativeProps({style: {fontSize: "10"}});
this['text-1'].setNativeProps({style: {fontSize: "20"}});
this['text-2'].setNativeProps({style: {fontSize: "30"}});
}
render() {
return (
<View style={styles.container}>
{
this.state.speciallist.map((item, i)=>(
<Text
key={`text-${i}`}
ref={(thisItem) => this[`text-${i}`] = thisItem}
>
{item}
</Text>
))
}
</View>
);
}
}
导出默认类App扩展React.Component{
建造师(道具){
超级(道具);
此.state={
特别提示:['aaa','bbb','ccc']
}
}
componentDidMount(){
这个['text-0'].setNativeProps({style:{fontSize:“10”});
这个['text-1'].setNativeProps({style:{fontSize:{20}});
这个['text-2'].setNativeProps({style:{fontSize:{30}});
}
render(){
返回(
{
this.state.specialist.map((项,i)=>(
此[`text-${i}`]=thisItem}
>
{item}
))
}
);
}
}
获取此错误无法读取未定义的属性“setNativeProps”
一些内容。。。是否已使用将函数绑定到类,并且函数是否在呈现后运行?我更新了一个完整的例子。。。您可以在componentDidMount中检查setNativeProps
以在渲染后更改样式。仍然无法读取未定义的属性“setNativeProps”hi,我尝试按照您的changestyle函数进行操作,它给了我此错误TypeError:_this[(“项-2”)].setNativeProps不是一个函数
您很可能没有定义,因为componentDidMount()
在执行之前被调用。添加计时器可能会有所帮助。
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
speciallist: ['aaa', 'bbb', 'ccc']
}
}
componentDidMount() {
this['text-0'].setNativeProps({style: {fontSize: "10"}});
this['text-1'].setNativeProps({style: {fontSize: "20"}});
this['text-2'].setNativeProps({style: {fontSize: "30"}});
}
render() {
return (
<View style={styles.container}>
{
this.state.speciallist.map((item, i)=>(
<Text
key={`text-${i}`}
ref={(thisItem) => this[`text-${i}`] = thisItem}
>
{item}
</Text>
))
}
</View>
);
}
}