在此電話號碼國家/地區代碼中,如何按地區自動設定國家/地區代碼。就像我在美國打開網站一樣,它會自動顯示國家代碼 1,如果我在印度打開網站,它會自動顯示國家代碼 91。就像天氣 API 一樣,是否有任何 API 應該自動檢查國家代碼
import React from "react";
import PhoneInput, {isValidPhoneNumber
} from "react-phone-number-input";
export default function App() {
const [fields, setFields] = React.useState([{ value: null }]);
function handleChange(i, event) {
if (event) {
const values = [...fields];
values[i].value = event;
setFields((v) => values);
}
}
return (
<div className="App">
{fields.map((field, idx) => (
<PhoneInput
key={idx}
id="phoneNumbers1"
type="text"
placeholder="Enter phone number "
value={field.value || ""}
defaultCountry="IN"
international
name="phoneNumbers"
autoComplete="off"
onChange={(e) => handleChange(idx, e)}
/>
))}
<button
type="button" >
Phone Number
</button>
</div>
);
}
uj5u.com熱心網友回復:
為了檢測國家,React 應用程式需要使用 IP-to-Location 服務(如IPRegistry)查找 IP 地址
這是一個帶有 IPRegistry 的客戶端示例:
const getCountryBtn = document.getElementById("getCountry");
const countryNameElement = document.getElementById("country");
getCountryBtn.onclick = function() {
fetch('https://api.ipregistry.co/?key=tryout')
.then(function (response) {
return response.json();
})
.then(function (payload) {
countryNameElement.innerHTML = payload.location.country.name;
});
}
<html>
<body>
<button id="getCountry">Get Country</button>
<div id="country"></div>
</body>
</html>
一旦國家名稱可用,就可以在 React 組件中將其對應的國家代碼設定為默認值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/390094.html
標籤:javascript 反应 接口
