초보자 경고! :)저는 설정을 Data 에서 아이를 구한 다음 전달하는 부모를 사용하여 구성 요소 formReducer 및 파견 하지만 부모 data.항목()을 비롯한 다양한 기능이 제공됩니다!
ChildComponent.js
function ChildComponent({signed, fileAttached}){
const { dispatch } = useContext(ContactFormContext);
const changeHandler = (event) => {
const formData = new FormData();
formData.append('File', event.target.files[0]);
dispatch({ type: "FILE_ATTACHED", payload: formData })
};
return (
<>
<div>
<input type="file" name="file" onChange={changeHandler} />
</div>
</>);
}
ParentComponent.js
function useFormProgress(fileAttached) {
function goForward() {
const currentStep = 1;
let appvariables = [
{
"key": "PUID",
"value": "a2sd"
},
{
"key": "ApplicationNames",
"value": "Trello, abc"
}
];
switch(currentStep) {
case 0:
break;
case 1:
console.log(fileAttached);
if(fileAttached != null)
sendEmail("Resignation Letter", appvariables, fileAttached);
break;
}
}
return [goForward];
}
function sendEmail(templateName, variables, attachment){
console.log("sending email...");
const requestBody = {
"templateName": templateName,
"recipients": [
"[email protected]"
],
"variables": variables,
"files": attachment
};
fetch('https://localhost:5001/api/Email',{
method:'Post',
body: JSON.stringify(requestBody),
headers:{'Content-Type': 'application/json'},
});
}
const initialState = {
signed: "",
fileAttached: null
};
function formReducer(state, action) {
switch (action.type) {
case "SIGNED":
return { ...state, signed: action.payload };
case "FILE_ATTACHED":
return {...state, fileAttached: action.payload};
default:
throw new Error();
}
}
function ParentComponent() {
const [state, dispatch] = useReducer(formReducer, initialState);
const { signed, fileAttached } = state;
const steps = [<ChildComponent {...{signed, fileAttached}}/>];
const [goForward] = useFormProgress(fileAttached);
return (
<ContactFormContext.Provider value={{ dispatch }}>
<div>{steps[0]}
<div><button onClick={e => {
e.preventDefault();
goForward();
}}
> Parent Button
</button>
</div>
</div>
</ContactFormContext.Provider>
);
}
ContactFormContext.js
const ContactFormContext = React.createContext();
스위치에서 문을 위(ParentComponent),습니다.로그(FileAttached)쇼 Data 와 0 항목(이미지를 참조하십시오 attached),도 API 를 요청이 성공하지 못합니다.!
당신이 그것을 밖으로 시도할 수 있습니다 in https://jscomplete.com/playground
컨텍스트에 추가에서 최고
어린이 추가 구성 요소는 코드
추가 parentcomponent 코드
다음 줄을 추가
ReactDOM.render(<ParentComponent/>, mountNode);
MyAPI 방법
[HttpPost]
public JsonResult Get(EmailRequest email)
{
//the request never comes here
}
EmailRequest.cs
public class EmailRequest
{
public string TemplateName { get; set; }
public string[] Recipients { get; set; }
public List<Variables> Variables { get; set; }
public FormFileCollection files { get; set; }
}