我正在用 react-native 制作一個計算器應用程式。我正在創建具有地圖功能的計算器按鈕,但當然每個按鈕看起來都一樣,是否可以更改單個元素的樣式,或者我應該更改按鈕的創建方式。這是我的“示例”按鈕
import React, {Component} from "react";
import { StyleSheet, Text , TouchableOpacity, } from "react-native";
export default class InputButton extends React.Component{
render() {
const{value,handleOnPress} = this.props;
return (
<TouchableOpacity
style={styles.container}
onPress={()=> handleOnPress(value)}>
<Text style={styles.text}>{value}</Text>
</TouchableOpacity>
);
} }
const styles = StyleSheet.create(
{
container:{
flex:1,
margin: 1,
backgroundColor: 'black',
justifyContent:"center",
alignItems: 'center'
},
text:{
fontSize: 30,
color: 'white',
fontWeight: 'bold'
}
});
這就是我在主要組件中回傳整個按鈕布局的功能:
renderButtons = () =>{
console.log(SCREEN_WIDTH " " SCREEN_HEIGHT)
if(SCREEN_HEIGHT > SCREEN_WIDTH){
let layouts = buttons.map((buttonRows,index)=>{
let rowItem = buttonRows.map((buttonItems,buttonIndex)=>{
return <InputButton
value={buttonItems}
handleOnPress={handleInput.bind(buttonItems)}
key={'btn-' buttonIndex}/>
});
return <View style={styles.inputRow} key={'row-' index}>{rowItem}</View>
});
return layouts
}
else
{
let layouts = buttons_landscape.map((buttonRows,index)=>{
let rowItem = buttonRows.map((buttonItems,buttonIndex)=>{
return <InputButton
value={buttonItems}
handleOnPress={handleInput.bind(buttonItems)}
key={'btn-' buttonIndex}/>
});
return <View style={styles.inputRow} key={'row-' index}>{rowItem}</View>
});
return layouts
}
}
我正在使用這些陣列來制作按鈕布局:
const buttons = [
['AC','DEL'],
['7','8','9','/'],
['4','5','6','-'],
['1','2','3','*'],
['0','.','=',,' ']
];
const buttons_landscape = [
['DEL','x!','e',' /-','%','AC'],
['10^x','√','2','8','9','/'],
['log10','e^x','4','5','6','-'],
['x^2','ln','1','2','3','*'],
['x^3','π','0','.','=',' ']
];
我的問題是如何更改創建按鈕和布局的方式,以便每個單個按鈕和布局都具有獨特的屬性或更改單個按鈕的樣式
uj5u.com熱心網友回復:
例如,您可以替換
return <View style={styles.inputRow} key={'row-' index}>{rowItem}</View>
沿著這些路線的東西
return <View style={someFunction(buttonItems, buttonIndex)} key={'row-' index}>{rowItem}</View>
在哪里someFunction回傳預期的樣式(默認為styles.inputRow,我猜)。
(此外,您的else塊是否與塊幾乎相同if,唯一的區別是buttonsv. buttons_landscape?如果它接受按鈕作為引數會更好,而不是重復相同的 8 行代碼)。
uj5u.com熱心網友回復:
您可以分解RowItem成它自己的組件并提供樣式,就好像它是一個單獨的行專案,然后將結果映射到RowItem.
function RowItem() {
return (
<button
onClick={xxx}
className="xxx"
>
{props.value}
</button>
);
}
function Buttons() {
return (
<table>
<thead>
...
</thead>
<tbody>
{props.buttons.map((button) => (
<RowItem button={button} key={button.id} />
)
}
</tbody>
</table>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/347521.html
標籤:javascript 反应原生
