[英]function as JSX - React Native
我希望這個 function 顯示在 JSX 代碼中
function getValue() {
const QuestionChild = ['zara','whats up1','have u ever been in uk1']
const randomItem = QuestionChild[Math.floor(Math.random() * QuestionChild.length)];
console.log(randomItem)
return randomItem
}
控制台日志顯示此結果但無法在代碼中顯示
這是 JSX:
<TouchableOpacity>
<View style={styles.btnBack}><Text style={styles.smallwowo}>Back</Text></View>
</TouchableOpacity>
<View style={styles.box}>
<Text>{getValue}</Text>
<TouchableOpacity onPress={()=> {getValue} }>
<View style={styles.btn}><Text style={styles.wowo}>Next</Text></View>
</TouchableOpacity>
單擊下一步按鈕時,它應該從問題數組中返回隨機選擇的字符串
編輯使用鈎子並將getValue()
與狀態相關的問題分開:
讓您的getValue
function 與原來的相同。
在組件頂部的某處:
const [randomValue, setRandomValue] = useState(getValue());
然后在下面的某個地方創建一個新的onPress
處理程序:
const onGetNewValue = () => setRandomValue(getValue());
然后在您的onPress
聲明中:
<TouchableOpacity onPress={onGetNewValue}>
而你實際顯示價值的地方是
<Text>{randomValue}</Text>
老答案:
首先,要實際顯示值,您需要實際調用 function,所以使用
<Text>{getValue()}</Text>
接下來,要讓按鈕按下更改值,您需要將值存儲在 state 中,這將觸發重新渲染。 有不同的方法可以做到這一點,但我會在你的構造函數中建議,創建
this.state = { randomValue: getValue() }
然后在getValue
做
...
const randomItem = QuestionChild[Math.floor(Math.random() * QuestionChild.length)];
this.setState({ randomValue: randomItem });
然后改為使用
<Text>{this.state.randomValue}</Text>
現在,每次單擊按鈕時,都會將一個新值存儲到 state,並且您的組件將使用新的 state 值重新渲染。
您應該存儲一些 state——無論是通過useState
還是通過有狀態組件——並讓getValue
function 更改為 state。
然后你會做<TouchableOpacity onPress={getValue}>
,而不是onPress={()=> {getValue} }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.